Click here to Skip to main content
15,909,742 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
When I do some thing simple like

double result = 3.1*4.1;


the result is 12.709999999999999

I would have expected 12.710000000000000


Is this normal for C#?
Posted
Updated 13-Dec-09 7:03am
v2

This is normal, floating point numbers cannot always depict an accurate representation of a value. If you want to display the number rounded then the ToString() method offers that capability.
 
Share this answer
 
There is a classic text, What Every Computer Scientist Should Know About Floating-Point Arithmetic[^] by David Goldberg that should help you understand what's happening here. It's not specific to C#, but rather the IEEE 754 standard for floating-point numbers that C# uses.

Suffice to say, it is normal, merely a common rounding error, similar to what you might have encountered in grade school when trying to represent the result of an expression such as 10 / 3 in decimal form...
 
Share this answer
 
v2
I had the same problem. The only solution I found is to convert the values to decimals, multiply them and after that convert to Double. That's expensive, but if no other solution is available, is acceptable.
 
Share this answer
 
Comments
Toli Cuturicu 23-Aug-10 10:43am    
Reason for my vote of 2
Non-problem, non-solution!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900