浮点数/浮点数=奇怪的结果 [英] Float / Float = strange result
问题描述
我有两个值,一个来自用户输入,另一个来自DB.
I have two values, one from user input and another from DB.
var userinput = form["someInput"];
var valuefromDB = GetValue(someNumber);
public float? GetValue(int id){
return (float?) db.table.where(p=> p.id == id).select(p=> p.Value).SingleOrDefault();
}
userinput的字符串值为"1",而fromDB的value值为float的0.001.
userinput have value "1" as string, while valuefromDB havevalue 0.001 as float.
所以1/0.001 = 1000
so 1 / 0.001 = 1000
但是我的C#代码给了我999.999939;
but my c# code give me 999.999939 as result;
var final = float.Parse(userinput) / valuefromDB
当我将"2"作为用户输入值时,结果是正确的2000 ...
when i have "2" as user input value, result is correct, 2000...
推荐答案
That's because not all decimal numbers can be accurately represented in binary (which is the representation that float
uses). The solution is to format the result to the desired number of decimal places, which will cause it to be rounded and displayed "correctly" as a consequence.
更新:要格式化 float
以便显示,请查看此示例页面.
Update: To format a float
for display, take a look at this MSDN reference page and this page of examples.
这篇关于浮点数/浮点数=奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!