NSNumberFormatter only rounds to 3 decimal places
Asked Answered
H

2

35

I'm trying to use NSNumberFormatter to round a number to 5 decimal places in an iPhone app, but [formatter stringFromNumber:] always returns strings rounded to 0.001 (3 decimal places). What am I doing wrong?

formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[formatter setSecondaryGroupingSize:3];
[formatter setRoundingIncrement:[NSNumber numberWithDouble:0.00001]];
Harrelson answered 1/5, 2009 at 4:15 Comment(0)
R
77

Try -setMaximumFractionDigits: and -setMinimumFractionDigits:

These configure the number of digits after the decimal separator.

Ribbonwood answered 1/5, 2009 at 13:10 Comment(3)
Thank you Nathan! I must be missing something while reading the docs, but how do these differ from setMaximumSignificantDigits: and setMinimumSignificantDigits: (aside from the word Significant <grin>)?Asafoetida
Fraction digits are numbers after the decimal place. Significant digits is the overall precision of the number. So 12.345 has 5 significant digits and 3 fraction digits. Whereas 0.0012 has 2 significant digits and 4 fraction digits. set(min/max)SignificantDigits: are useful for scientific style output: 123000 would be 1.23E5 with 3 significant digits.Ribbonwood
Note that if using [ formatter setMinimumSignificantDigits ] you must first call [ formatter setUsesSignificantDigits: TRUE ];Brayton
T
2

Try [formatter setFormat:@"0.00000"]; instead of setRoundingIncrement:.

Toluidine answered 1/5, 2009 at 4:29 Comment(4)
I don't think setFormat: is available on the iPhone. See #416537Harrelson
Actually, I take that back. setFormat:@"0.00000" does work, but it doesn't round... I always get 5 numbers past the decimal--e.g., 0.10000, when I really only want 0.1 in that case.Harrelson
Ah, sorry, I misunderstood what you were trying to accomplish.Toluidine
I wasn't that clear about what I was trying to accomplish. Your response was helpful. Thank you.Harrelson

© 2022 - 2024 — McMap. All rights reserved.