Jak*_*ade 50 .net c# vb.net string-formatting
如何将小数值格式化为逗号/点后面的单个数字的字符串,以及值小于100的前导空格?
例如,十进制值12.3456应" 12.3"与单个前导空格一样输出.10.011会的" 10.0".123.123是"123.1"
我正在寻找一种解决方案,它适用于标准/自定义字符串格式,即
decimal value = 12.345456;
Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern.
Run Code Online (Sandbox Code Playgroud)
nem*_*esv 87
这种模式{0,5:###.0}应该有效:
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"
Run Code Online (Sandbox Code Playgroud)
另一个带有字符串插值(C#6+)的字符串:
double x = 123.456;
$"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals
Run Code Online (Sandbox Code Playgroud)
表达式返回: " 123.4560"
value.ToString("N1");
Run Code Online (Sandbox Code Playgroud)
更改小数位数的数字.
编辑:错过了填充位
value.ToString("N1").PadLeft(1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49529 次 |
| 最近记录: |