1

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?

rounak
  • 8,669
  • 3
  • 38
  • 58
zapdroid
  • 512
  • 5
  • 15
  • 1
    This issue is very common with other languages as well - although computers try, they aren't perfect with precision (unfortunately for us humans :P). A simplistic fix would be to round the decimal after conversion – Vineet Kosaraju Jun 23 '15 at 20:38
  • possible duplicate of [Objective C Issue With Rounding Float](http://stackoverflow.com/questions/6333711/objective-c-issue-with-rounding-float) – Peter Tutervai Jun 23 '15 at 20:43
  • Thanks Bucco. When I adding or multiplying two decimal value after that rounding up. But I wonder why this value changes and you said common issues :) I got my answer thanks. Do you know is there anyway how to get original value not rounding. – zapdroid Jun 23 '15 at 20:44
  • It is not the same question like you said @PeterTutervai. – zapdroid Jun 23 '15 at 20:50
  • @zapdroid I do realize that you asked a more or less different question, but I do think that the answer is there in the linked question - your value isn't changed, thats just how numbers are represented on computers. – Peter Tutervai Jun 24 '15 at 05:59

2 Answers2

2

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.

Artal
  • 7,695
  • 2
  • 21
  • 29
-2

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

MMiroslav
  • 1,462
  • 18
  • 31