C# 浮点数到十进制的转换

发布于 2024-08-28 17:44:48 字数 236 浏览 3 评论 0原文

有什么聪明的方法可以将浮点数转换

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

情场扛把子 2024-09-04 17:44:48

为时已晚,第 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.

骑趴 2024-09-04 17:44:48

这可能是一个编译器错误,因为看起来有效的浮点数应该直接转换为十进制。但它不会失去分辨率。
将 125.609375 从浮点转换为十进制将失去分辨率。
但是,将其从浮点转换为双精度,然后将双精度转换为十进制将保持分辨率。

    float float_val = 125.609375f;

    decimal bad_decimal_val = (decimal)float_val;   //125.6094

    double double_val = (double)float_val;
    decimal good_decimal_val = (decimal)double_val;

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.

    float float_val = 125.609375f;

    decimal bad_decimal_val = (decimal)float_val;   //125.6094

    double double_val = (double)float_val;
    decimal good_decimal_val = (decimal)double_val;
圈圈圆圆圈圈 2024-09-04 17:44:48

当您写入 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.

终难遇 2024-09-04 17:44:48

你尝试过吗?

decimal.TryParse()

http://forums.asp.net/t/1161880.aspx

float/double 和decimal 之间没有隐式转换。隐式数值转换始终保证不损失精度或大小,并且不会导致异常。

have you tried?

decimal.TryParse()

http://forums.asp.net/t/1161880.aspx

There are no implicit conversions between float/double and decimal. Implicit numeric conversions are always guaranteed to be without loss of precision or magnitude and will not cause an exception.

岁月静好 2024-09-04 17:44:48

试试这个

float y = 20;

decimal x = Convert.ToDecimal(y/100);

print("test: " + x);

try this

float y = 20;

decimal x = Convert.ToDecimal(y/100);

print("test: " + x);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文