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:
NSLog(@"%.2f", answer);
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:
int maxDigitsAfterDecimal = 3; // here's where you set the dp
NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
[nf setMaximumFractionDigits:maxDigitsAfterDecimal];
NSString * trimmed = [nf stringFromNumber:[NSNumber numberWithDouble:3.14159]];
NSLog(@"%@", trimmed); // in this case, 3.142
[nf release];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With