[英]How do I convert a double value to a value of type decimal with a fixed number of decimal places in .NET
[英]truncate the double number and convert it to a string with the desired number of significant figures or decimal places
我使用C#在windows 7中構建了一個程序。我想將小數點后的所有小數轉換為零雙精度數據。
比如我想實現這個function:
輸入 21.123 輸出 21.000
輸入15.8 輸出15.0
輸入178.51 輸出178.00
輸入3.4679 輸出3.0000
所有輸入數據都是雙精度類型。
output 將寫入 csv。
string data = '';
double WidthVal, LengthVal, AreaVal = 2.1, 3.45, 6.789;
data += ',' + Math.Truncate(WidthVal);
data += ',' + Math.Truncate(LengthVal);
data += ',' + Math.Truncate(AreaVal);
using (StreamWriter sw = File.AppendText(filename + ".csv"))
{
sw.WriteLine(data);
sw.Close();
}
csv 中所需的 output:2.0、3.00、6.000
以下代碼可以實現您想要的
string Y(double x)
{
var s = x.ToString(CultureInfo.InvariantCulture);
var i = s.IndexOf(".");
return i == -1 ? s : Math.Truncate(x).ToString($"N{s.Length - 1 - i}");
}
請注意,例如0.56
將轉換為"0.00"
。 此外,根據您的需要,您可能還想多玩一點 output 數字格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.