views:

1210

answers:

2

Hi, 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??? Many thanks.

formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[formatter setSecondaryGroupingSize:3];
[formatter setRoundingIncrement:[NSNumber numberWithDouble:0.00001]];
+2  A: 

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

smorgan
I don't think setFormat: is available on the iPhone. See http://stackoverflow.com/questions/416037/iphone-nsnumberformatter-setformat
ChadK
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.
ChadK
Ah, sorry, I misunderstood what you were trying to accomplish.
smorgan
I wasn't that clear about what I was trying to accomplish. Your response was helpful. Thank you.
ChadK
+3  A: 

Try -setMaximumFractionDigits: and -setMinimumFractionDigits: (links require login).

Nathan Kinsinger
I think that's what I was looking for. Many thanks.
ChadK
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>)?
Joe D'Andrea
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.
Nathan Kinsinger