C# 将双精度格式化为两位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18418668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting a double to two decimal places
提问by Dan Cairnes
I have been trying to make the answer this prints out to be to two decimal places. All the math involved has to stay at that format of two decimal places. I have tried a few things and I am not sure what to change to make this work.
我一直试图将打印出来的答案保留到小数点后两位。所有涉及的数学都必须保持两位小数的格式。我已经尝试了一些事情,但我不确定要改变什么才能使这项工作发挥作用。
double pdt1 = 239.99;
double pdt1Total;
double pdt2 = 129.75;
double pdt2Total;
double pdt3 = 99.95;
double pdt3Total;
double pdt4 = 350.89;
double pdt4Total;
double wage = 200;
double percentage = 9;
double total;
double answer;
double i = 100;
double a;
double b;
double c;
double d;
Console.Write("Enter number sold of product #1: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #2: ");
b = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #3: ");
c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #4: ");
d = Convert.ToInt32(Console.ReadLine());
pdt1Total = a * pdt1;
pdt2Total = b * pdt2;
pdt3Total = c * pdt3;
pdt4Total = d * pdt4;
total = (pdt1Total + pdt2Total + pdt3Total + pdt4Total);
string.Format("{0:0.00}", total);
string.Format("{0:0.00}", answer = (total * percentage / i) + wage);
Console.WriteLine("Earnings this week: "+answer+"");
采纳答案by Damith
string.Format
will not change the original value, but it will return a formatted string. For example:
string.Format
不会改变原始值,但会返回一个格式化的字符串。例如:
Console.WriteLine("Earnings this week: {0:0.00}", answer);
Note: Console.WriteLine
allows inline string formatting. The above is equivalent to:
注意:Console.WriteLine
允许内联字符串格式化。以上相当于:
Console.WriteLine("Earnings this week: " + string.Format("{0:0.00}", answer));
回答by Karl Anderson
You can round a double
to two decimal places like this:
您可以double
像这样将a 舍入到两位小数:
double c;
c = Math.Round(c, 2);
But beware rounding will eventually bite you, so use it with caution.
但要注意四舍五入最终会咬你,所以谨慎使用它。
Instead use the decimal
data type.
而是使用decimal
数据类型。
回答by Ehsan
Well, depending on your needs you can choose any of the following. Out put is written against each method
好吧,根据您的需要,您可以选择以下任何一种。输出是针对每个方法编写的
You can choose the one you need
你可以选择你需要的
This will round
这将圆
decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
This will ensure that 2 decimal places are written.
这将确保写入 2 个小数位。
d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
if you want to write commas you can use this
如果你想写逗号,你可以使用这个
d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
if you want to return the rounded of decimal value you can do this
如果你想返回四舍五入的十进制值,你可以这样做
d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
回答by Peter
Since you are working in currency why not simply do this:
既然你在货币工作,为什么不简单地这样做:
Console.Writeline("Earnings this week: {0:c}", answer);
This will format answer as currency, so on my machine (UK) it will come out as:
这会将答案格式化为货币,因此在我的机器(英国)上,它将显示为:
Earnings this week: £209.00
本周收益:£209.00
回答by anhoppe
I would recomment the Fixed-Point ("F") format specifier (as mentioned by Ehsan). See the Standard Numeric Format Strings.
我会推荐定点(“F”)格式说明符(如 Ehsan 所述)。请参阅标准数字格式字符串。
With this option you can even have a configurable number of decimal places:
使用此选项,您甚至可以拥有可配置的小数位数:
public string ValueAsString(double value, int decimalPlaces)
{
return value.ToString($"F{decimalPlaces}");
}
回答by philoroussel
The problem is that when you are doing additions and multiplications of numbers all with two decimal places, you expect there will be no rounding errors, but remember the internal representation of double is in base 2, not in base 10 ! So a number like 0.1 in base 10 may be in base 2 : 0.101010101010110011... with an infinite number of decimals (the value stored in the double will be a number N with :
问题在于,当您对所有小数点后两位的数字进行加法和乘法时,您预计不会出现舍入错误,但请记住 double 的内部表示是以 2 为底的,而不是以 10 为底的!因此,像 0.1 以 10 为基数的数字可能以 2 为基数: 0.101010101010110011... 具有无限个小数(存储在 double 中的值将是一个数字 N,其中:
0.1-Math.Pow(2,-64) < N < 0.1+Math.Pow(2,-64)
As a consequence an operation like 12.3 + 0.1 may be not the same exact 64 bits double value as 12.4 (or 12.456 * 10 may be not the same as 124.56) because of rounding errors. For example if you store in a Database the result of 12.3 +0.1 into a table/column field of type double precision number and then SELECT WHERE xx=12.4 you may realize that you stored a number that is not exactly 12.4 and the Sql select will not return the record; So if you cannot use the decimal datatype (which has internal representation in base 10) and must use the 'double' datatype, you have to do some normalization after each addition or multiplication :
因此,由于舍入错误,诸如 12.3 + 0.1 之类的操作可能与 12.4 不完全相同(或 12.456 * 10 可能与 124.56 不同)。例如,如果您将 12.3 +0.1 的结果存储在双精度数字类型的表/列字段中,然后 SELECT WHERE xx=12.4 您可能会意识到您存储的数字不完全是 12.4 并且 Sql select 将不归还记录;因此,如果您不能使用十进制数据类型(它具有以 10 为基数的内部表示)并且必须使用“双”数据类型,则必须在每次加法或乘法后进行一些标准化:
double freqMHz= freqkHz.MulRound(0.001); // freqkHz*0.001
double amountEuro= amountEuro.AddRound(delta); // amountEuro+delta
public static double AddRound(this double d,double val)
{
return double.Parse(string.Format("{0:g14}", d+val));
}
public static double MulRound(this double d,double val)
{
return double.Parse(string.Format("{0:g14}", d*val));
}
回答by Kamran Bigdely
double d = 3.1493745;
string s = $"{d:0.00}"; // or $"{d:#.##}"
Console.WriteLine(s); // Displays 3.15