NSDecimalNumber round long numbers
Asked Answered
D

2

5

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?

Deoxyribose answered 16/9, 2010 at 13:29 Comment(0)
C
3

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.

Chong answered 13/3, 2012 at 9:6 Comment(0)
P
1

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

Pino answered 16/12, 2014 at 0:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.