如何在 C# 中将整数 999999999 转换为浮点数 999999999.0 而不是 1000000000.0?

How to convert integer 999999999 to float 999999999.0 instead of 1000000000.0 in C#?

在 C# 中,要将 int 转换为 float,我们只需要执行类似 float floatNumber = intNumberConvert.ToSingle(intNumber) 的操作。但是,当遇到大数字如999999999时,系统无法正确转换该数字,而是将其转换为不需要的数字1E+09。现在的问题是,是否可以将那个大整数转换为想要的浮点数?

32 位浮点数不能准确地表示那么大的整数:它只有 24 位来表示(格式中隐含了一位)。在 24 位中,您可以表示 16777215。16777216 也适合,因为它是 2 的幂。 999999999 不能精确表示为最多 24 位乘以 2 的幂的数字。

在 SO 上查看此答案:

有关详细信息,请查找有关 IEEE 浮点 32 位和 64 位格式的详细信息。

你可以使用 decimal 类型吗?

Console.WriteLine(999999999.0f.ToString("N"));
Console.WriteLine(999999999.0m.ToString("N"));;

打印

1,000,000,000.00
999,999,999.00

reference甚至有一个非常大的例子

In this example, the output is formatted by using the currency format string. Notice that x is rounded because the decimal places exceed [=15=].99. The variable y, which represents the maximum exact digits, is displayed exactly in the correct format.

public class TestDecimalFormat
{
    static void Main()
    {
        decimal x = 0.999m;
        decimal y = 9999999999999999999999999999m;
        Console.WriteLine("My amount = {0:C}", x);
        Console.WriteLine("Your amount = {0:C}", y);
    }
}
/* Output:
    My amount = .00
    Your amount = ,999,999,999,999,999,999,999,999,999.00
*/