NSNumber to NSDecimalNumber conversion issue

2k views Asked by At

When I convert NSNumber to NSDecimalNumber this conversion is frequently not true.

I have a number like 92.43 when I convert this value to decimal or double [number decimalValue] or [number doubleValue] value changes as 92.4299999999..

I did so many things like [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue] its always returns "92.429999" to this number.

How do I use NSNumber originalValue decimal or double it is not matter I want to use "92.43" this number as "92.43". And Why this value changing?

2

There are 2 answers

1
MMiroslav On

If you just need to print this number then try:

NSLog(@"%.2f", decimalNumber);

This will round 92.4299999999.. on two decimals and result will be:

92.43

0
Artal On

Why is this happening?

A simplified explanation would be that it is related to how computers perform the calculations and how floating point numbers are being represented. Most floating point numbers simply does not have an accurate enough representation since they require infinite number of digits to be represented, hence the rounding (also known as roundoff or rounding error).

What can you do?

If you really need to perform accurate calculations (calculating prices for example), you should not work with NSNumber at all, but use NSDecimalNumber all the way and use it for all calculation. The safest way would be to create it from a string, for example:

NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:@"92.34567891"];

If accuracy doesn't matter, you can alway format the result to a fixed number of decimal places. In this case, you might also want to look into NSDecimalNumberHandler to define the rounding behaviour.