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