NSDecimalNumber round long numbers

好久不见. 提交于 2021-02-16 13:14:10

问题


I'm trying to get NSDecimalNumber to print out large numbers, 15 or more digits. At 15 digits I see 111,111,111,111,111. Above 15 digits I see 1,111,111,111,111,110 even though the number being formatted is 1111111111111111.

An example to illustrate my problem:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumSignificantDigits:25];
[formatter setUsesSignificantDigits:true];

NSDecimalNumber* test = [NSDecimalNumber decimalNumberWithString:@"12345678901234567890"];

NSString* output = [formatter stringFromNumber:test]; 
NSLog( @"num value: %@", test ); 
NSLog( @"str value: %@", output );

And the output looks like:

2010-09-16 09:24:16.783 SimpleCalc[739:207] num value: 12345678901234567890
2010-09-16 09:24:16.784 SimpleCalc[739:207] str value: 12,345,678,901,234,600,000

What silly thing have I missed?


回答1:


The problem here is that NSNumberFormatter does not handle NSDecimalNumbers internally, they are converted to double and you are seeing the resulting loss in precision. From the docs:

The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.

You should probably be taking a look at the - (NSString *)descriptionWithLocale:(NSDictionary *)locale method on NSDecimalNumber.




回答2:


Or NSDecimalString(). Take your NSDecimalNumber (e.g. myDecimalNumber), extract the NSDecimal via decimalValue (NSDecimal decimal = [myDecimalNumber decimalValue]) and create an NSString with the NSString *myString = NSDecimalString(decimal) function.

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/index.html#//apple_ref/c/func/NSDecimalString



来源:https://stackoverflow.com/questions/3727142/nsdecimalnumber-round-long-numbers

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