用C#格式化一个带点和小数的数字

本文关键字:小数 数字 一个 格式化 | 更新日期: 2023-09-27 17:58:52

我首先需要。(点)然后逗号(,)。

例如,1234567这是一个示例数字或货币我想要1.234.567,00有人能给我一个答案吗。

用C#格式化一个带点和小数的数字

如果执行代码的计算机上的区域性设置符合您的愿望,您可以简单地使用ToString重载作为:

    double d = 1234567;
    string res = d.ToString("#,##0.00");  //in the formatting, the comma always represents the group separator and the dot the decimal separator. The format part is culture independant and is replaced with the culture dependant values in runtime.

如果显示器必须与区域性无关,则可以使用特定的数字formatinfo:

 var nfi = new NumberFormatInfo { NumberDecimalSeparator = ",", NumberGroupSeparator = "." };
    double d = 1234567;
    string res = d.ToString("#,##0.00", nfi); //result will always be 1.234.567,00

这看起来像是一种外币格式。根据你真正想要的,可能有多种方法可以做到这一点。以下MSDN链接为您提供了完整的文档:

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#CFormatString

一个有效的例子如下:

        string xyz = "1234567";
        // Gets a NumberFormatInfo associated with the en-US culture.
        NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
        nfi.CurrencyDecimalSeparator = ",";
        nfi.CurrencyGroupSeparator = ".";
        nfi.CurrencySymbol = "";
        var answer = Convert.ToDecimal(xyz).ToString("C3", 
              nfi);

xyz=1.234.567000

您也可以动态更改应用程序的区域性。如果您查看"格式化特定区域性的数字数据",并查看标记为"格式化欧元国家的货币"的部分,它将详细解释如何做到这一点。

基本上,你会想改变文化使用:

Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

然后,您可以使用.ToString()方法,将"c"作为参数传递,表示您希望将字符串格式化为当前区域性的货币:

double d = 1234567;
string converted = d.ToString("c");

这应该会给你想要的东西。如果你不想在所有工作中都使用欧式数字,那么一定要让文化倒退。