Search code examples
objective-cios7

Objective C: decimalNumberByMultiplyingByPowerOf10 looses precision on perfect division


I have scenario where I need to show amount with two precision values always. Server sends me values in cents and I changes it to dollars using below written code.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   NSDecimalNumber *shiftedDecimalNumber = [[[NSDecimalNumber alloc] initWithString:@"100.00"]  decimalNumberByMultiplyingByPowerOf10:-2];

    NSLog (@"%@",shiftedDecimalNumber);
   [pool drain];
   return 0;
}

This code works fine when I have values like 101 etc because now when I will use decimalNumberByMultiplyingByPowerOf10 with power -2 I will get 1.01 (101/100)

But if I will have 100 or 200 as value then decimalNumberByMultiplyingByPowerOf10 with power -2 gives me 1 or 2 respectively.

How can I ensure a decimal value with two precision always?

Thanks in advance.


Solution

  • The precision is not "lost". It's just the trailing zeroes that are not printed by NSLog() when logging your NSDecimalNumber (to be exact, the trailing zeros are not printed by -description of NSDecimalNumber, that is called under the bonnet).

    Try getting a double representation of the number, then log it using a format specifiers that requires two decimal places to be always included: NSLog (@"%.2f", [shiftedDecimalNumber doubleValue]);

    Note: the conversion to double is only necessary because the format specifier used requires a double as an argument. Of course there might be other ways to print the number.