2

I have a strange issue using double numbers in C# . NET here is my test:

double my_value = 0.49;

the problem is that the variable value shown is instead 0.48999999999999999 I do not need to display 0.49 using Math.Round() function; I need to exactly store this value.

Thank you.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
elnath78
  • 137
  • 1
  • 13
  • Always useful link... http://pages.cs.wisc.edu/~rkennedy/exact-float – xanatos Sep 04 '13 at 10:49
  • If you look at the answers in linked question, you may be better off using a `Decimal` type. However, be warned! Double may "look" bad but it will be far more precise if you're doing lots of calculations with that value. However if you're simply storing it or doing simple add/subtract calculations with it then Decimal will serve you well. – Binary Worrier Sep 04 '13 at 10:50
  • @BinaryWorrier - depends on what kind of calculations. For example in financial calculations, using double would be a horrible mistake. For calculations in physics, double would be perfect and decimal would be a mistake. – Corak Sep 04 '13 at 10:55
  • @BinaryWorrier - i need to stor the item price for paypal checkout, on another website i didnt had to deal with decimal so recycled the code and found that error. I do not need to make any calculation so i guess decimal is my choice to pass the price. – elnath78 Sep 04 '13 at 11:53
  • @Corak: Depends on the type of financial calculations. For years I wrote projection software for Actuaries, rolling up Insurance/Assurance polices by many decades. There were hundreds of thousands of calculations on those values until the projected end of term. Small rounding errors at the start could lead to large discrepancies by the end. Using a decimal type there would have made the final figures meaningless. Unfortunately one size does not fit all :) – Binary Worrier Sep 04 '13 at 14:19

3 Answers3

7

Welcome to floating point precision. Use the decimal type if you want more precision.

decimal my_value = 0.49m;

If you want to learn more on why this is I recommend you read this article - What Every Computer Scientist Should Know About Floating-Point Arithmetic

Lloyd
  • 29,197
  • 4
  • 84
  • 98
  • Decimal isn't fixed precision, as the number and location of the decimal point are encoded within the number. It's just that the Decimal type has more precision than Float or Double. – HTTP 410 Sep 04 '13 at 11:03
  • @RoadWarrior You are right of course, I've updated it. – Lloyd Sep 04 '13 at 11:35
1

Use decimal instead, double is floating binary point type.

decimal my_value = 0.49m;

Useful links;

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Do not use the double type when you need to use exact values. That is the domain of the decimal type

decimal my_value = 0.49m;
SWeko
  • 30,434
  • 10
  • 71
  • 106