如何避免在NSNumberFormatter四舍五入(How to avoid rounding o

2019-08-17 09:19发布

我想有一些字符串,最大2位小数的精度,而其余的只而小数修剪掉,而不是四舍五入起来的。 例如:

I have: 123456.9964

I want: 123456.99 -> Just want to trim rest of the decimal places

我曾尝试是:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat: 123456.9964]];
 NSLog(@"%@", numberAsString);

没有什么可以设置舍入模式为“无”。 还有什么我可以做与修剪十进制数字沿着保持十进制形式的格式? 任何帮助将不胜感激。 谢谢。

Answer 1:

对我来说,以下工作:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
// optional - [numberFormatter setMinimumFractionDigits:2];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
NSNumber *num = @(123456.9964);
NSString *numberAsString = [numberFormatter stringFromNumber:num];
NSLog(@"%@", numberAsString);

输出为:123,456.99

你的问题的部分原因是使用的numberWithFloat:不是numberWithDouble: 您的号码有太多的数字float



Answer 2:

您可以使用此

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setRoundingMode:NSNumberFormatterRoundDown];
[numberFormatter setMaximumFractionDigits:2];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble: 123456.9964]];
NSLog(@"%@", numberAsString);


Answer 3:

[numberFormatter setRoundingMode: NSNumberFormatterRoundDown];

使用此代码。



Answer 4:

you can also just use round() and then convert it into a string afterward

var y = round(100 * 123456.8864) / 100

var x:String = String(format:"%.2f", y)
println("x: \(x)")

would print x: 123456.89, rounding the 8 to a 9.



文章来源: How to avoid rounding off in NSNumberFormatter