Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)可能的重复:c# -如何将一个十进制值四舍五入到小数点后两位(对于页面上的输出)
I have an XML file with decimal values of temperature in string format. Examples:
我有一个带有字符串格式的十进制温度值的XML文件。例子:
<temp>30</temp>
<temp>40.6</temp>
I retrieve the temperature using LINQ like this
我用LINQ来获取温度
temperature = d.Element("temp").Value
How do I revise this code so that the value is rounded up or down appropriately before assigning to temperature in string format. This means, in the first example, temperature will be "30" and in the 2nd example, temperature will be "41". Thanks.
如何修改此代码,以便在以字符串格式分配温度之前适当地对值进行四舍五入。这意味着,在第一个例子中,温度将是“30”,在第二个例子中,温度将是“41”。谢谢。
4 个解决方案
#1
3
Your current Values are strings.
当前值是字符串。
This ought to work:
这应该工作:
string temperature =
double.Parse( d.Element("temp").Value, CultureInfo.InvariantCulture)
.ToString("0.");
#2
1
You can use:
您可以使用:
Math.Round(double.Parse(d.Element("temp").Value))
#3
1
double temp = Double.Parse(d.Element("temp").Value;
string displayTemp = temp.ToString("0.");
#4
1
One thing to watch for when rounding is which kind of rounding are you trying to do. For example the following:
当四舍五入的时候要注意的一件事是你想做什么。例如以下:
var num = "2.5";
Console.WriteLine(Decimal.Parse(num).ToString("0."));
Console.WriteLine(Math.Round(Decimal.Parse(num),0));
outputs: 3 2
输出:3 - 2
You would need to do the following to output 3 using Math.Round:
您需要使用Math.Round对输出3进行以下操作:
Console.WriteLine(Math.Round(Decimal.Parse(num),0, MidpointRounding.AwayFromZero));
#1
3
Your current Values are strings.
当前值是字符串。
This ought to work:
这应该工作:
string temperature =
double.Parse( d.Element("temp").Value, CultureInfo.InvariantCulture)
.ToString("0.");
#2
1
You can use:
您可以使用:
Math.Round(double.Parse(d.Element("temp").Value))
#3
1
double temp = Double.Parse(d.Element("temp").Value;
string displayTemp = temp.ToString("0.");
#4
1
One thing to watch for when rounding is which kind of rounding are you trying to do. For example the following:
当四舍五入的时候要注意的一件事是你想做什么。例如以下:
var num = "2.5";
Console.WriteLine(Decimal.Parse(num).ToString("0."));
Console.WriteLine(Math.Round(Decimal.Parse(num),0));
outputs: 3 2
输出:3 - 2
You would need to do the following to output 3 using Math.Round:
您需要使用Math.Round对输出3进行以下操作:
Console.WriteLine(Math.Round(Decimal.Parse(num),0, MidpointRounding.AwayFromZero));