【发布时间】:2019-01-29 23:46:30
【问题描述】:
能否请一些更有经验的人解释一下我今天发现的这个奇怪的错误? 当我用我的 C# 脚本加载表数据时,我得到了奇怪的数量。
事实证明,问题在于类似函数的输出不同:
string amount_in_string = "1234567,15";
double amount_in_double = double.Parse(amount_in_string);
float amount_in_float = float.Parse(amount_in_string);
//amount_in_double = 1234567.15;
//amount_in_float = 1234567.13;
当 float 和 double 是相似类型(浮点)时,为什么我会得到如此不同的结果。像这样少量的精度可以产生影响吗?
【问题讨论】:
-
您应该为此使用
decimal,而不是double或float。 -
@Fildor @ron "amount" 只是一个数量,不一定是货币。 OP 没有指明货币。还有,乖一点,不用
! -
@Fildor 你应该解释一下为什么他不应该使用浮点类型
-
@MickyD 你是对的,“金额”也可以是非货币的。评论被撤回。旁注:我对“!”不是那么敏感。我来自哪里他们(当使用单数“!”,而不是“!!!!!!”)不会引起冒犯。
-
JonSkeet has a very good explanation on this subject,基本上
double和float是二进制点类型(例如,double或float永远不能等于 0.1)和decimal是十进制(以 10 为底)点类型。如果您正在寻找点精度,您应该改用decimal!
标签: c# .net types floating-point precision