浮点数/浮点数=奇怪的结果 [英] Float / Float = strange result

查看:101
本文介绍了浮点数/浮点数=奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个值,一个来自用户输入,另一个来自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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆