C# - 将 NumberFormatInfo 与 Convert.ToDouble 一起使用到 return double

C# - Using NumberFormatInfo with Convert.ToDouble to return double

在我的应用程序中我有国际化,所以我们有很多方法来处理格式化。 其中一个应该收到一个双精度并将其格式化为小数点后两位和 return a double。为此,我们根据所选文化使用 NumberFormatInfo

问题是我无法让 Convert.ToDouble 以我想要的方式与 NumberFormatInfo 一起工作。基本上我想知道的是为什么这样:

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        var myDouble = 9.983743;

        var nfi = new NumberFormatInfo() {
            NumberDecimalDigits = 2
        };

        Console.WriteLine("Original value: " + myDouble);
        Console.WriteLine("Converted value: " + Convert.ToDouble(myDouble, nfi));
    }
}

版画

Original value: 9.983743
Converted value: 9.983743 // Should be 9.98

如果可能的话,我怎样才能只使用 NumberFormatInfo 得到我想要的结果。

谢谢,

来自MSDN

The NumberDecimalDigits property is used with the "F" and "N" standard format strings without a precision specifier in numeric formatting operations.

默认为通用格式 (G)。所以这会给你想要的结果:

Console.WriteLine(myDouble.ToString("N", nfi));

但是,2 无论如何都是默认值。最好明确指定它:

Console.WriteLine(myDouble.ToString("N2", NumberFormatInfo.InvariantInfo));

更新:

Yeah but I do need to return a double from my method.

现在我明白了。在你的位置,我也会 return 原来的 double。如果您的 API 的消费者想要 display/store 它作为一个包含两位数的字符串,那么他有责任对其进行格式化。

如果您真的想省略精度的最后一位和 return 修改后的值,请改用 Math.Round(但我不建议这样做)。

您声明要 return 一个 double,小数点后只有 2 位数字。因此,你不是格式化你是rounding:

Math.Round(myDouble, 2)

9.98

将 double 转换为 double 不会改变任何东西,double 始终是双精度,您不能更改小数位数。

double 没有格式,当您使用 ToString() 方法显示 double 时,格式开始发挥作用,如 taffer 所述。

您可以将它四舍五入以将前 2 之后的所有数字设置为零,但您不能删除数字。