variable decimal places in .Net string formatters?

后端 未结 8 1507
感动是毒
感动是毒 2020-12-29 04:49

Fixed decimal places is easy

String.Format(\"{0:F1}\", 654.321);

gives

654.3

How do I feed the number of

相关标签:
8条回答
  • 2020-12-29 05:48

    Probably the most efficient approach for formatting a single value:

    int decimalPlaces= 2;
    double value = Math.PI;
    string formatString = String.Format("F{0:D}", decimalPlaces);
    value.ToString(formatString);
    
    0 讨论(0)
  • 2020-12-29 05:51

    Use NumberFormatInfo:

    Console.WriteLine(string.Format(new NumberFormatInfo() { NumberDecimalDigits = 2 }, "{0:F}", new decimal(1234.567)));
    Console.WriteLine(string.Format(new NumberFormatInfo() { NumberDecimalDigits = 7 }, "{0:F}", new decimal(1234.5)));
    
    0 讨论(0)
提交回复
热议问题