简体   繁体   English

C# 浮点到十进制转换

[英]C# float to decimal conversion

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);

It's too late, the 8th digit was lost in the compiler. 现在为时已晚,第8位数字在编译器中丢失了。 The float type can store only 7 significant digits. float类型只能存储7位有效数字。 You'll have to rewrite the code, assigning to double or decimal will of course solve the problem. 你必须重写代码,分配为double或decimal当然会解决问题。

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. 将125.609375从float转换为十进制将失去分辨率。 However, converting it from float to double and then double to decimal will keep resolution. 但是,将它从float转换为double然后将其转换为double将保持分辨率。

    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;

have you tried? 你有没有尝试过?

decimal.TryParse()

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

There are no implicit conversions between float/double and decimal. float / double和decimal之间没有隐式转换。 Implicit numeric conversions are always guaranteed to be without loss of precision or magnitude and will not cause an exception. 隐式数字转换始终保证不会丢失精度或幅度,并且不会导致异常。

You lost precision the moment you've written 711989.98f. 你写完711989.98f的那一刻就失去了精确度。

711989.98 is decimal. 711989.98是十进制的。 With f in the end you are asking the compiler to convert it to float. 最后使用f,您要求编译器将其转换为float。 This conversion cannot be done without losing precision. 在不失去精度的情况下无法完成此转换。

What you probably want is decimal d = 711989.98m. 你可能想要的是十进制d = 711989.98m。 This will not lose precision. 这不会失去精确度。

try this尝试这个

        float y = 20;

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

        print("test: " + x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM