Possible Duplicate:
Rounding numbers in Objective-C
objective -C : how to truncate extra zero in float?
Correcting floating point numbers
In Objective C, I have a double which receives the answer to a calculation as shown:
double answer = a / b;
The double variable can sometimes be a whole integer but can also be a fraction e.g.
NSLog(@"%f", answer)
This can return 2.000000 or 5.142394 or 2.142000.
I was wondering if there was a way to edit the decimal places so that the trailing 0’s are not visible for example:
2.000000 would be 2
5.142394 would be 5.142394
2.142000 would be 2.142
How can this be done?
If you’d like to hard-code the number of decimal places you’re after, this would give you two decimal places:
Read more about format specifiers here:
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
Alternatively, if you’d like to change the number of decimal places on-the-fly, consider using the NSNumberFormatter class: