[英]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.