Format decimal value to string with leading spaces

后端 未结 4 875
鱼传尺愫
鱼传尺愫 2020-12-14 14:39

How do I format a decimal value to a string with a single digit after the comma/dot and leading spaces for values less than 100?

For example, a decimal value of

相关标签:
4条回答
  • 2020-12-14 15:01

    Another one with string interpolation (C# 6+):

    double x = 123.456;
    $"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals
    

    Expression returns: " 123.4560"

    0 讨论(0)
  • 2020-12-14 15:04

    All above solution will do rounding of decimal, just in case somebody is searching for solution without rounding

    decimal dValue = Math.Truncate(1.199999 * 100) / 100;
    dValue .ToString("0.00");//output 1.99
    
    0 讨论(0)
  • 2020-12-14 15:06

    This pattern {0,5:###.0} should work:

    string.Format("{0,5:###.0}", 12.3456) //Output  " 12.3"
    string.Format("{0,5:###.0}", 10.011)  //Output  " 10.0" 
    string.Format("{0,5:###.0}", 123.123) //Output  "123.1"
    string.Format("{0,5:###.0}", 1.123)   //Output  "  1.1"
    string.Format("{0,5:###.0}", 1234.123)//Output "1234.1"
    
    0 讨论(0)
  • 2020-12-14 15:13
    value.ToString("N1");
    

    Change the number for more decimal places.

    EDIT: Missed the padding bit

    value.ToString("N1").PadLeft(1);
    
    0 讨论(0)
提交回复
热议问题