在 C# 中将双精度舍入到小数点后两位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2357855/
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
Round double in two decimal places in C#?
提问by sanjeev40084
I want to round up double value in two decimal places in c# how can i do that?
我想在 c# 中四舍五入两位小数的双值,我该怎么做?
double inputValue = 48.485;
after round up
四舍五入后
inputValue = 48.49;
Related: c# - How do I round a decimal value to 2 decimal places (for output on a page)
相关:c# - 如何将十进制值四舍五入到 2 个小数位(用于页面上的输出)
采纳答案by Alex LE
This works:
这有效:
inputValue = Math.Round(inputValue, 2);
回答by recursive
回答by nandin
Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
回答by Gage
You should use
你应该使用
inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
Math.Round rounds a double-precision floating-point value to a specified number of fractional digits.
Math.Round 将双精度浮点值四舍五入到指定的小数位数。
Specifies how mathematical rounding methods should process a number that is midway between two numbers.
指定数学舍入方法应如何处理介于两个数字之间的数字。
Basically the function above will take your inputvalue and round it to 2 (or whichever number you specify) decimal places. With MidpointRounding.AwayFromZero
when a number is halfway between two others, it is rounded toward the nearest number that is away from zero.There is also another option you can use that rounds towards the nearest even number.
基本上,上面的函数将获取您的输入值并将其四舍五入到 2(或您指定的任何数字)小数位。随着MidpointRounding.AwayFromZero
当一个数字是中间两个人之间,它向四舍五入,从零距离最接近的数字。您还可以使用另一个选项,将其舍入到最接近的偶数。
回答by reza.cse08
you can try one from below.there are many way for this.
你可以从下面尝试一个。有很多方法可以做到这一点。
1.
value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
inputvalue=Math.Round(123.4567, 2) //"123.46"
3.
String.Format("{0:0.00}", 123.4567); // "123.46"
4.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
回答by Diwas
Another easy way is to use ToString with a parameter. Example:
另一种简单的方法是使用带有参数的 ToString。例子:
float d = 54.9700F;
string s = d.ToString("N2");
Console.WriteLine(s);
Result:
结果:
54.97
回答by John-Perez
Use an interpolated string, this generates a rounded up string:
使用内插字符串,这会生成一个四舍五入的字符串:
var strlen = 6;
$"{48.485:F2}"
Output
输出
"48.49"