views:

506

answers:

2

How can I get a float or real value from integer division? For example:

double result = 30/233;

yields zero. I'd like the value with decimal places.

How can I then format so only two decimal places display when used with a string?

+6  A: 

You could just add a decimal to either the numerator or the denominator:

double result = 30.0 / 233;
double result = 30 / 233.0;

Typecasting either of the two numbers also works.

As for the second part of the question, if you use printf-style format strings, you can do something like this:

sprintf(str, "result = %.2f", result);

Bascially, the ".2" represents how many digits to output after the decimal point.

htw
Thanks. I wasn't sure how to use that with the char* but this works just as well [NSString stringWithFormat:@"result = %.2f", result].
4thSpace
Yeah, that's the great thing about Cocoa—there are a lot of places where printf-style formatted strings are utilized (NSLog being the most prominent of them all, I'd say).
htw
Just be careful about subtle differences, like the %s being encoded as the system encoding rather than whatever the current encoding calls for and %S being a big-endian UTF-16 string instead of wchar_t.
Jason Coco
+1  A: 

If you have an integer (not integer constant):

int i = 20;
int j = 220;
double d = i/(double)j;
Maciej Piechotka