When converting from NSNumber to double, the number from 2.3 turns into 2.2999999998 double accum = [self.accumulator doubleValue];

Back this chip does not work. Will output 2.299999998

Here you can somehow do without crutches or not? Thanks in advance for your reply.

  • How is the accumulator created? - AlexDenisov
  • @property (strong, nonatomic) NSNumber * accumulator; - am1kk
  • one
    Ok, and how is it created? self.accumulator = ???; In general, there are suspicions that it is created from a float, and then double is obtained from there. And here on this conversion accuracy is lost. - AlexDenisov

1 answer 1

When converting from NSNumber to double, the number from 2.3 turns into 2.2999999998

Here it is not a matter of translation, but of the impossibility of accurately presenting some decimal fractions in binary form.

Here you can somehow do without crutches or not?

Use NSDecimalNumber. NSDecimalNumber is the successor of NSNumber, but it stores the mantissa and the exponent separately in integer variables: the mantissa in the int variable, and the exponent in the short variable.

 NSNumber *number = [NSDecimalNumber decimalNumberWithMantissa:23 exponent:-1 isNegative:NO]; 

Do not make the number float or double (i.e. do not use doubleValue and floatValue), otherwise you will lose accuracy.