[英]Format custom numeric string with fixed character count
我需要將固定數量的字符轉換為固定格式的任何數字。 均值1500和-1.5或0.025必須具有相同的長度。 我還必須以這種形式給出格式: Format = "{???}";
當我鍵入Format = "{0000}";
我可以將1500限制為“ 1500”,但是-1.5->“ -0001.5”表示我在該點之后的數字過多。
負號可以通過Format = "{ 0.0;-0.0; 0.0}"
。
如何確定不同數字的計數?
字符串的長度無關緊要,最重要的是相等的長度。
例子:
1500 -> " 1500.000" or " 1500"
-1500 -> "-1500.000" or "- 1500" or " -1500"
1.5 -> " 1.500" or " 1.5"
-0.25-> " -0.250" or "- 0.25"
0.00005 -> " 0.000" or " 0"
150000-> " 150000.0" or " 150000"
15000000 " 15000000"
編輯:
我想設置圖表的Y軸格式。 我不能使用諸如value.ToString("???")
類的東西,我需要使用chartArea.AxisY.LabelStyle.Format = "{???}";
為什么不使用格式? “ F3”強制小數點后3位,PadLeft確保總長度
Double value = 1500.0;
// 3 digits after decimal point, 9 characters length
String result = value.ToString("F3").PadLeft(9, ' ');
0 -> 0.000
1500.0 -> 1500.000
-1500.0 -> -1500.000
-0.25 -> -0.250
另一種(類似)可能性是String.Format:
Double value = 1500.0;
// Put value at place {0} with format "F4" aligned to right up to 9 symbols
String result = String.Format("{0:9,F4}", value);
嘗試> result = Math.Round(yourValue, 3);
在此處查看完整參考!
您無法通過簡單的格式功能來實現
string result = string.Empty;
var array = dec.ToString().Split('.');
if (dec > 0)
{
result = array[0].PadLeft(9).Remove(0, 9);
if (array.Count() > 1)
{
result += '.' + array[1].PadRight(3).Remove(3);
}
}
else
{
result = "-"+array[0].PadLeft(9).Remove(0, 9);
if (array.Count() > 1)
{
result += '.' + array[1].PadRight(3).Remove(3);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.