代码之家  ›  专栏  ›  技术社区  ›  shsteimer

如何将十进制格式设置为C中可编程控制的小数位数?

  •  7
  • shsteimer  · 技术社区  · 16 年前

    如何将数字格式化为固定的小数位数(保留尾随零),其中位数由变量指定?

    例如

    int x = 3;
    Console.WriteLine(Math.Round(1.2345M, x)); // 1.234 (good)
    Console.WriteLine(Math.Round(1M, x));      // 1   (would like 1.000)
    Console.WriteLine(Math.Round(1.2M, x));    // 1.2 (would like 1.200)
    

    请注意,由于我想通过编程控制位置的数量,此字符串.format将不起作用(当然我不应该生成格式字符串):

    Console.WriteLine(
        string.Format("{0:0.000}", 1.2M));    // 1.200 (good)
    

    我应该包括microsoft.visualBasic和use吗 FormatNumber ?

    我希望这里缺少一些明显的东西。

    5 回复  |  直到 14 年前
        1
  •  12
  •   Nick Berardi    16 年前

    尝试

    decimal x = 32.0040M;
    string value = x.ToString("N" + 3 /* decimal places */); // 32.004
    string value = x.ToString("N" + 2 /* decimal places */); // 32.00
    // etc.
    

    希望这对你有用。见

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

    更多信息。如果你发现附件有点粗糙,尝试一下:

    public static string ToRoundedString(this decimal d, int decimalPlaces) {
        return d.ToString("N" + decimalPlaces);
    }
    

    然后你可以打电话

    decimal x = 32.0123M;
    string value = x.ToRoundedString(3);  // 32.012;
    
        2
  •  4
  •   Lukas Cenovsky    14 年前

    尝试此操作可以动态创建自己的格式字符串,而不必使用多个步骤。

    Console.WriteLine(string.Format(string.Format("{{0:0.{0}}}", new string('0', iPlaces)), dValue))
    

    在步骤中

    //Set the value to be shown
    decimal dValue = 1.7733222345678M;
    
    //Create number of decimal places
    int iPlaces = 6;
    
    //Create a custom format using the correct number of decimal places
    string sFormat = string.Format("{{0:0.{0}}}", new string('0', iPlaces));
    
    //Set the resultant string
    string sResult = string.Format(sFormat, dValue);
    
        3
  •  2
  •   Joel Coehoorn    16 年前

    有关格式字符串帮助,请参阅以下链接:
    http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
    http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

    你想要这个:

    Console.WriteLine(Math.Round(1.2345M, x).ToString("F" + x.ToString()));
    

    此外,如果需要的话.toString调用将为您回传,以便您可以跳过 Math.Round 打电话来,就这么做:

    Console.WriteLine(1.2345M.ToString("F" + x.ToString()));
    
        4
  •  1
  •   Matt Grande    16 年前

    像这样的事情应该处理它:

    int x = 3;
    string format = "0:0.";
    foreach (var i=0; i<x; i++)
        format += "0";
    Console.WriteLine(string.Format("{" + format + "}", 1.2M));
    
        5
  •  0
  •   Brian M. Hunt    16 年前

    方法:

    private static string FormatDecimal(int places, decimal target)
            {
                string format = "{0:0." + string.Empty.PadLeft(places, '0') + "}";
                return string.Format(format, target); 
            }