Float value
-
I am passing float value to a varibale, but I am not getting correct value float Val1=4.6; float Val2 = Val1;//getting 4.5999999 I am getting 4.5999999, How can I get the return value as 4.6?
This is due to floating point precision. See here[^] (or google for it) for more information. If you really need more precision, you can always use a double (but I doubt that you need it).
Cédric Moonen Software developer
Charting control [v3.0] OpenGL game tutorial in C++ -
I am passing float value to a varibale, but I am not getting correct value float Val1=4.6; float Val2 = Val1;//getting 4.5999999 I am getting 4.5999999, How can I get the return value as 4.6?
Welcome to floating point math! Your result is typical and is why the #1 rule on doing floating point math is to never depend on the value being exact. You will need to compensate or use a higher precision number type, depending on what you are trying to accomplish. In most situations the difference in calculated values is not significant, but sometimes it is. The worst resolution problems usually occur when you subtract 2 numbers that are close, then do further manipulations. If you are checking the value with
if
statements, for example, then you need to check that the value is within a reasonable tolerance. Search around using Google and Bing for "floating point precision" and you should find lots of information.CQ de W5ALT
Walt Fair, Jr., P. E. Comport Computing Specializing in Technical Engineering Software
-
I am passing float value to a varibale, but I am not getting correct value float Val1=4.6; float Val2 = Val1;//getting 4.5999999 I am getting 4.5999999, How can I get the return value as 4.6?
Read here.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"Man who follows car will be exhausted." - Confucius
-
Read here.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"Man who follows car will be exhausted." - Confucius
Wow! Fantastic article: even those who already know the topic should read (and learn) it!
-
I am passing float value to a varibale, but I am not getting correct value float Val1=4.6; float Val2 = Val1;//getting 4.5999999 I am getting 4.5999999, How can I get the return value as 4.6?