NSDecimalNumber round long numbers
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?
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
.
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
精彩评论