ios7 - Objective C: decimalNumberByMultiplyingByPowerOf10 looses precision on perfect division -
i have scenario need show amount 2 precision values always. server sends me values in cents , changes 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 have values 101 etc because when use decimalnumberbymultiplyingbypowerof10 power -2 1.01 (101/100)
but if have 100 or 200 value decimalnumberbymultiplyingbypowerof10 power -2 gives me 1 or 2 respectively.
how can ensure decimal value 2 precision always?
thanks in advance.
the precision not "lost". it's trailing zeroes not printed nslog()
when logging nsdecimalnumber (to exact, trailing zeros not printed -description
of nsdecimalnumber
, called under bonnet).
try getting double
representation of number, log using format specifiers requires 2 decimal places included: nslog (@"%.2f", [shifteddecimalnumber doublevalue]);
note: conversion double necessary because format specifier used requires double argument. of course there might other ways print number.
Comments
Post a Comment