3

I have an interesting problem with a specific conversion. When I try to convert the string "0,3" or "0.3", according to the UICulture, to a Double value, the result is 0,29999999. I have not yet found a solution, in order to receive the result 0,3.

There is any way to have the same values after the conversion?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Costel
  • 43
  • 4
  • 8
    This has been asked many, many, many times. `0.3` is not representable exactly as a double value because of the way decimal values are stored in a binary computer. – mellamokb Jan 18 '13 at 13:52
  • See Marc's answer. Of note perhaps, it's called floating point representation not presentation. http://en.wikipedia.org/wiki/Floating_point – kenny Jan 18 '13 at 13:54

1 Answers1

14

double cannot represent every value. It guarantees to represent integers, but that is about it. If you need something more like "human" approximation of numbers, use decimal:

decimal val = decimal.Parse("0.3");

Note: decimal also doesn't represent every value - but the way it does the approximation tends to be more like how people expect numbers to work. In particular, double is virtually useless for things like currency.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    A bit more detail provided by Jon Skeet [here](http://stackoverflow.com/a/618596/18192). Click the linked articles for an in-depth explanation. The short answer is that `decimal` is in base 10, which matches 0.3. `double` is in base 2, which does not. – Brian Jan 18 '13 at 18:20