-2

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 that problem, but I still get values such as "7.6" and "35" (which I want to be "7.60" and "35.00")

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"?

UPDATE

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.:

UPDATE 2

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").

enter image description here

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 4
    Member for more than 5 years and still asking poor, research lacking questions... – L.B Oct 20 '16 at 20:57
  • 1
    So, you want to round your value to 2 decimal places? Why not just use the `Math.Round(value, 2)` function and then `.ToString("F2")` that? – Geoff James Oct 20 '16 at 20:58
  • Take a look at this post: http://stackoverflow.com/questions/10749506/two-decimal-places-using-c-sharp. – tyson Oct 20 '16 at 21:01

3 Answers3

2

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 :)

Geoff James
  • 3,122
  • 1
  • 17
  • 36
0

You can use the #.00 format instead.

SledgeHammer
  • 7,338
  • 6
  • 41
  • 86
0

Because it's Excel, I had to tell the range/cell exactly how to behave, like so:

totalPriceCell.NumberFormat = "#,##0.00";
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862