![](/img/trans.png)
[英]Formatting a decimal value with ToString() to have commas as thousand separators where the amount of decimal places is unknown
[英]C# formatting a number with thousand separators but keeping the decimal places count as is
我想將千位分隔符添加到double
數,但希望保留小數位,即不希望四舍五入。
#,#
正在解決我添加千位分隔符的問題,但如何保留小數位? #,#
去掉 . 之后的部分.
.
我不能使用任何文化或類似的東西 & 我打電話給 function 的開發人員只給了我一種通過傳遞參數strFormat
來更改格式的方法。
我確實檢查了其他帖子甚至文檔,但不知何故無法弄清楚。
string strFormat = "#,#";
string str = double.parse("912123456.1123465789").ToString(strFormat);
//Expected here 912,123,456.1123465789
//Actual Output 912,123,456
//912123456.123 should give 912,123,456.123
//912123456.1 should give 912,123,456.1
//912123456.1123465789 should give 912,123,456.1123465789
//912123456 should give 912,123,456
如果您知道最大小數位數,例如 10,則使用:
string strFormat = "#,#0.##########";
更新:
這個最大數量是已知的。 根據Microsoft 文檔,Double 值最多具有 15 個小數位的精度(包括小數點前后)。 超過 15 位將四舍五入。
因此,如果您必須調用“double.parse”的方法並且只能發送格式,那么這是您可以做的最好的事情:
string strFormat = "#,#0.###############";
好吧,在查看了Microsoft上的文檔之后,似乎沒有特定的方法允許數字中出現浮點數 position - 格式字符串中的所有字符都是字符占位符。
我建議您要么使用非常討厭的預定數量的#
來設置小數點 position 的寬度,要么使用稍微少一點(或者可能更多,取決於您的前景)的討厭選項,將所有數字讀入一個數組,確定最長的小數 position,然后使用結果構建#
的格式。
歸根結底,這是一個單一的格式字符串,您可以將其放置到位、測試並確保其正常工作,然后稍后回來並在找到更好的替代方案時進行修復。
此外,這是您可以將字符串放入配置設置並根據需要進行更改的事情之一 - 更加靈活。
老實說,在性能和編寫程序的宏偉計划中,這是一件非常小的事情。
從技術上講,Udi Y 得到了我的投票!
您可以為每個數字動態計算格式:
public static void Main()
{
var number = 1234.12312323123;
var format = GetNumberFormat(number);
Console.WriteLine(number.ToString(format));
}
public static string GetNumberFormat(double number)
{
var numberAsString = number.ToString();
var decimalPartSize = numberAsString.Substring(numberAsString.LastIndexOf('.') + 1).Length;
return $"N{decimalPartSize}";
}
所以
number = 1234.12312323123
會給你1,234.12312323123
。 也適用於負數。 此外,當我們使用字符串時,不會有任何舍入錯誤或精度偽影。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.