Format decimal value to string with leading spaces

谁说胖子不能爱 提交于 2019-11-28 22:17:51

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"

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"

value.ToString("N1");

Change the number for more decimal places.

EDIT: Missed the padding bit

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

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