Format decimal value to string with leading spaces

穿精又带淫゛_ 提交于 2019-11-27 14:17:23

问题


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 12.3456 should be output as " 12.3" with single leading space. 10.011 would be " 10.0". 123.123 is "123.1"

I'm looking for a solution, that works with standard/custom string formatting, i.e.

decimal value = 12.345456;
Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern.

回答1:


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"



回答2:


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"




回答3:


value.ToString("N1");

Change the number for more decimal places.

EDIT: Missed the padding bit

value.ToString("N1").PadLeft(1);



回答4:


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


来源:https://stackoverflow.com/questions/8293392/format-decimal-value-to-string-with-leading-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!