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.

5
  • Always useful link... pages.cs.wisc.edu/~rkennedy/exact-float Commented Sep 4, 2013 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. Commented Sep 4, 2013 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. Commented Sep 4, 2013 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. Commented Sep 4, 2013 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 :) Commented Sep 4, 2013 at 14:19

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@RoadWarrior You are right of course, I've updated it.
1

Use decimal instead, double is floating binary point type.

decimal my_value = 0.49m;

Useful links;

Comments

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.