C# 浮点数到十进制的转换
有什么聪明的方法可以将浮点数转换
float f = 711989.98f;
为小数(或双精度)而不丢失精度?
我尝试过:
decimal d = (decimal)f;
decimal d1 = (decimal)(Math.Round(f,2));
decimal d2 = Convert.ToDecimal(f);
Any smart way to convert a float like this:
float f = 711989.98f;
into a decimal (or double) without losing precision?
I've tried:
decimal d = (decimal)f;
decimal d1 = (decimal)(Math.Round(f,2));
decimal d2 = Convert.ToDecimal(f);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为时已晚,第 8 位数字在编译器中丢失了。 float类型只能存储7位有效数字。您必须重写代码,分配给双精度或十进制当然可以解决问题。
It's too late, the 8th digit was lost in the compiler. The float type can store only 7 significant digits. You'll have to rewrite the code, assigning to double or decimal will of course solve the problem.
这可能是一个编译器错误,因为看起来有效的浮点数应该直接转换为十进制。但它不会失去分辨率。
将 125.609375 从浮点转换为十进制将失去分辨率。
但是,将其从浮点转换为双精度,然后将双精度转换为十进制将保持分辨率。
This may be a compiler bug because it seems like a valid float should convert directly to a decimal. but it wont without losing resolution.
Converting 125.609375 from float to decimal will lose resolution.
However, converting it from float to double and then double to decimal will keep resolution.
当您写入 711989.98f 时,您就失去了精度。
711989.98 是十进制。最后使用 f 时,您要求编译器将其转换为浮点型。这种转换不可能在不损失精度的情况下完成。
您可能想要的是十进制 d = 711989.98m。这不会失去精度。
You lost precision the moment you've written 711989.98f.
711989.98 is decimal. With f in the end you are asking the compiler to convert it to float. This conversion cannot be done without losing precision.
What you probably want is decimal d = 711989.98m. This will not lose precision.
你尝试过吗?
http://forums.asp.net/t/1161880.aspx
have you tried?
http://forums.asp.net/t/1161880.aspx
试试这个
try this