B. Clay Shannon - 10 months ago 55

C# Question

With this code:

`totalPriceCell.Value2 = TotalPrice;`

...I was getting values such as "3.14963245" which I want to be "3.15" instead.

So I used this code:

`totalPriceCell.Value2 = TotalPrice.ToString("#.##");`

...and that did solve

What can I do to accomplish this, outside of manually appending a "0" for vals such as "7.6" and manually appending ".00" for values such as "35"?

Niether suggestion worked, neither this:

`totalPriceCell.Value2 = TotalPrice.ToString("F2");`

...nor this:

`totalPriceCell.Value2 = Math.Round(TotalPrice, 2).ToString("F2");`

I still get "7.6" etc.:

It turns out to be an Excel problem, because when I added this:

`MessageBox.Show(Math.Round(TotalPrice, 2).ToString("F2"));`

...I did see values such as "7.60" (not "7.6").

Answer Source

It looks like you're trying to round the numbers to 2 decimal places, and *then* output the answer with trailing 0.

Just use the `Math.Round()`

function to round, and then display using the `.ToString("F2")`

format:

```
totalPriceCell.Value2 = Math.Round(TotalPrice, 2).ToString("F2");
```

`Math.Round(arg1, arg2)`

: Where 1st argument *(arg1)* is the value you want to round, and 2nd argument *(arg2)* is the decimal places you wish to round to.

`.ToString("F2")`

: Usage of `"F2"`

- *F* being the "fixed-point" format specified; *2* being the number of digits after the decimal point.

Hope this helps :)