Limiting decimal points to what is needed [duplica

2019-03-30 09:32发布

问题:

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?

回答1:

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];


回答2:

NSNumberFormatter is exactly what you're looking for. (my apologies if you aren't working with a Mac, I'll post a link to similar iOS docs later).

EDIT (by request): NSNumberFormatter is in fact available for iOS (the docs I posted above are the same for iOS), and has a few relevant properties that you should set. For one, it's numberStyle property should be set to NSNumberFormatterDecimalStyle (others include percent, banker, and spell-out). NSNumberFormatter also includes a roundingMode property, which in your case should be NSNumberFormatterRoundHalfEven. This will change your decimal to have the last digit rounded off, but it's the best way to get rid of those zeroes.