How to avoid rounding off in NSNumberFormatter

扶醉桌前 提交于 2020-01-01 08:37:22

问题


I am trying to have a number string with maximum 2 decimals precision, while rest decimals just trimmed off instead of rounding them up. For example:

I have: 123456.9964

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

What I have tried is:

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

There is nothing to set rounding mode as "none". What else can I do to maintain Decimal style formatting along with trimmed decimal digits? Any help will be appreciated. Thanks.


回答1:


The following works for me:

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

The output is: 123,456.99

Part of your problem is the use of numberWithFloat: instead of numberWithDouble:. Your number has too many digits for float.




回答2:


you can use this

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



回答3:


[numberFormatter setRoundingMode: NSNumberFormatterRoundDown];

Use this code.




回答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.



来源:https://stackoverflow.com/questions/15264109/how-to-avoid-rounding-off-in-nsnumberformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!