-2

I have a value, and I want to see only two digits on the decimal.

desired output = 5.49, but it still returns 5.49000000002

value = 5.49000000002;
double tempValue = (round(value*100))/100.0;

Also tried the following examples, still getting the same.

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundFloor];
double value = 5.49000000000002;
double x = [[formatter stringFromNumber:[NSNumber numberWithDouble:value]] doubleValue];
double y = [[NSString stringWithFormat:@"%.2f", value] doubleValue];
casillas
  • 16,351
  • 19
  • 115
  • 215
  • @Rob, This question is being marked as duplicate, but I am exactly using the same solution provided in this question, but the result is not what I expected. Therefore, I wanted to ask this question. – casillas Feb 11 '18 at 07:57
  • please show all the code that is related – itenyh Feb 11 '18 at 08:02
  • @Rob, I want to get directly `double` number, not `NSNumber`. Is it really necessary to convert `double` to `NSNumber` and apply formatter and then convert it back to `double`? Also I used the exact same solution, please check https://stackoverflow.com/questions/4985791/round-double-value-to-2-decimal-places/10102097#10102097. – casillas Feb 11 '18 at 08:03
  • Like that answer (and many, many others) have pointed out, floating point types, like `double` simply cannot accurately represent certain fractional decimal values, which is why you use number formatters (whether `NSNumberFormatter` or `NSString`'s `stringWithFormat`) to limit the output to a certain number of decimal places. Or, if you really need an accurate two decimal place value, don't use `double`, but use `NSDecimalNumber`. – Rob Feb 11 '18 at 08:12
  • @Rob, please check my updated question, still getting the same. – casillas Feb 11 '18 at 08:16
  • 1
    You're missing my point. You're assuming that `double` is capable of capturing the value 5.49 exactly. It simply can't. See [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). So, if you're concerned about showing the value to two decimal places, you use the aforementioned formatters. If you want to do math that precisely represents two decimal places and no more, then use `NSDecimalNumber`. But I know it seems implausible, but `double` simply cannot represent many numbers precisely to two decimal places. – Rob Feb 11 '18 at 08:20

1 Answers1

0

Sometimes doubles can't display a specific value. Due to being expressed in binary it will, sometimes, just end up being really close. You need to work less on the rounding there and more on truncating the output. Usually it doesn't matter, just use like printf or something to display the number of relevant bytes of the output. You can't hit every decimal perfectly in binary.

Tatarize
  • 10,238
  • 4
  • 58
  • 64