0

I try to convert (Decimal)0.9975 to string with (0.##) format in C# but it rounds the number to 1 instead of 0.99

Here is the code;

decimalValue.ToString("0.##");

How can I write the output as 0.99?

Jibran Khan
  • 3,236
  • 4
  • 37
  • 50
emreturan
  • 451
  • 1
  • 5
  • 18
  • That's because rounding .997 to .99 will cause .99 to 1. You can prove this by trying the same code with .9875. So the code is fine, what is wrong is your expectation. Do you need rounding or *truncation*? – Adam Houldsworth Jul 12 '13 at 09:37
  • I don't recommend going for `"0.##"`, because if your decimal does not have any floating values, for instance `10`, you will get `"10."`, which doesn't look nice at all – Nolonar Jul 12 '13 at 09:41

3 Answers3

3

I got this on SO long time back. I too was struck with something similar. I owe this post to him.

decimal d = 0.9975m;

decimal newDecimal = Math.Truncate((d*100))/100;

string result = string.Format("{0:N2}", newDecimal.ToString()); // OR

string result = newDecimal.ToString(); //This is simpler I guess.

Hope it helps.

Sandy
  • 11,332
  • 27
  • 76
  • 122
  • thank you. But I dont understand why we do this operations (d*100)/100 – emreturan Jul 12 '13 at 10:38
  • `Truncate(d*100)` will result in integer without rounding off. So we get `0.9975 * 100 = 99.75`. Then `Truncate(99.75) = 99`. Then `99/100 = 0.99`. And then we convert it to string. – Sandy Jul 12 '13 at 10:57
0

the other option is to accept the rounding but subtract 0.005 from the decimal

decimal d = 0.9975m;
string result = (d-0.005m).ToString("0.##");

(0.9975 - 0.005) = 0.9925;
0.9925 => 0.99
RoughPlace
  • 1,111
  • 1
  • 13
  • 23
0

use format

decimalValue.ToString("#0.0#");

The '#' will be updated if there is a value on the placeholder, if there is no value on the'#' placeholder, then this will be ignored, but the '0.0' will not be ignored.

or

var value = string.Format("{0:0.00}", decimalValue);

or

decimal decimalValue = 0.9975;
value.ToString("G3");

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Jegan
  • 1,227
  • 9
  • 16