C# 转换为双精度到两位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11213052/
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
converting to double to two decimal places
提问by user1483145
Hi i am a c# novice would someone politely tell me how to convert the values of this piece of code to a double/rounded decimal.. thanks in advance
嗨,我是 ac# 新手,有人会礼貌地告诉我如何将这段代码的值转换为双精度/四舍五入的小数.. 提前致谢
DataTable dtValues = new DataTable("GetValues");
strValueNumber = ValueNumber[0].ToString();
dtGetValues = SQLMethods.GetValues(strValueNumber);
total = 0;
for (int i = 0; i < dtValues.Rows.Count; i++)
{
total1 = total1 + Convert.ToInt32(dtGetValues.Rows[i]["total_1"]);
total2 = total2 + Convert.ToDouble(dtGetValues.Rows[i]["total_2l"]) * .45;
tbtotal1.Text = total1.ToString();
tbtotal2.Text = total2.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Error in returning selected Values. " +
"Processed with error:" + ex.Message);
}
}
采纳答案by Nikhil Agrawal
Use Math.Round
Math.Round(mydoublevalue, 2);
In your code
在你的代码中
tbtotal2.Text = Math.Round(total2, 2).ToString();
回答by Adil
Do it like this.
像这样做。
tbtotal1.Text = Math.Round(double.Parse(total1.ToString()), 2).ToString();
tbtotal2.Text = Math.Round(double.Parse(total2.ToString()), 2).ToString();
回答by Tyler
If you only want the value rounded for display as a string, you can also use String.Format.
如果您只想将值四舍五入以显示为字符串,您还可以使用String.Format。
tbtotal1.Text = String.Format("{0:0.##}", total1);
The text "{0:0.##}" describes how you want it to be formatted. The # indicates that ending zeroes should not be included (eg 1.2 stays the string "1.2"), if you instead do "{0:0.00}", two decimal places are included no matter what, so the double 1.2 would become "1.20".
文本“{0:0.##}”描述了您希望它的格式。# 表示不应该包含结尾零(例如 1.2 保持字符串“1.2”),如果您改为执行“{0:0.00}”,无论如何都会包含两位小数,因此双精度 1.2 将变为“1.20” ”。
回答by alexan
My answer is pretty late but for those out there like me who want:
to convert to double/decimal and also want the value to always show 2 decimal places (.00)asString
我的答案已经很晚了,但对于像我这样想要的人来说:
转换为双精度/十进制并且还希望该值始终显示 2 个小数位 (.00)作为String
tbtotal2.Text = Math.Round(total2, 2).ToString("#.00");
The below means two decimal places at all times.
以下始终表示两位小数。
"#.00"
The below means two decimal places if there is value.
如果有值,以下表示小数点后两位。
"#.##"

