objective-c NSNumberFormatter 只四舍五入到小数点后 3 位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/810161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:28:07  来源:igfitidea点击:

NSNumberFormatter only rounds to 3 decimal places

objective-ccocoa-touch

提问by ChadK

I'm trying to use NSNumberFormatterto 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?

我试图NSNumberFormatter在 iPhone 应用程序中使用将数字四舍五入到小数点后 5 位,但[formatter stringFromNumber:]总是返回四舍五入到 0.001(小数点后 3 位)的字符串。我究竟做错了什么?

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

回答by Nathan Kinsinger

Try -setMaximumFractionDigits:and -setMinimumFractionDigits:

尝试-setMaximumFractionDigits:-setMinimumFractionDigits:

These configure the number of digits after the decimal separator.

这些配置小数点分隔符后的位数。

回答by smorgan

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

试试 [格式化程序 setFormat:@"0.00000"]; 而不是 setRoundingIncrement:。