[英]Format decimal value to string with leading spaces
对于小于 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.
这种模式{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"
另一个使用字符串插值(C# 6+):
double x = 123.456;
$"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals
表达式返回: " 123.4560"
value.ToString("N1");
更改数字以获得更多小数位。
编辑:错过了填充位
value.ToString("N1").PadLeft(1);
许多好的答案,但这是我使用最多的(c# 6+):
Debug.WriteLine($"{height,6:##0.00}");
//if height is 1.23 => " 1.23"
//if height is 0.23 => " 0.23"
//if height is 123.23 => "123.23"
以上所有解决方案都会对小数进行四舍五入,以防万一有人正在寻找没有四舍五入的解决方案
decimal dValue = Math.Truncate(1.199999 * 100) / 100;
dValue .ToString("0.00");//output 1.99
注意“。” 使用 string.Format 时,可能是“,”,具体取决于区域设置。
string.Format("{0,5:###.0}", 0.9) // Output " .9"
string.Format("{0,5:##0.0}", 0.9) // Output " 0.9"
我最终使用了这个:
string String_SetRPM = $"{Values_SetRPM,5:##0}";
// Prints for example " 0", " 3000", and "24000"
string String_Amps = $"{(Values_Amps * 0.1),5:##0.0}";
// Print for example " 2.3"
非常感谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.