2

Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)

I have an XML file with decimal values of temperature in string format. Examples:

 <temp>30</temp>
 <temp>40.6</temp>

I retrieve the temperature using LINQ like this

 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.

Community
  • 1
  • 1
user776676
  • 4,265
  • 13
  • 58
  • 77

4 Answers4

3

Your current Values are strings.

This ought to work:

string temperature = 
   double.Parse( d.Element("temp").Value, CultureInfo.InvariantCulture)
   .ToString("0.");
H H
  • 263,252
  • 30
  • 330
  • 514
1

You can use:

 Math.Round(double.Parse(d.Element("temp").Value))
Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
1
double temp = Double.Parse(d.Element("temp").Value;

string displayTemp = temp.ToString("0.");
Jason
  • 86,222
  • 15
  • 131
  • 146
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

You would need to do the following to output 3 using Math.Round:

Console.WriteLine(Math.Round(Decimal.Parse(num),0, MidpointRounding.AwayFromZero));
Jim Wooley
  • 10,169
  • 1
  • 25
  • 43