Reputation: 2429
Am calculating small values in decimal, Expected result is = 345.00 but Result getting is = 345.0000
my code is this decimal temp= 6900 * ( 5 / 100);
temp = 345.0000 how to round this ? I want to show 345.00 ? whats my mistake here ?
I tried this code Math.Round(tempdiscountprice, 2);
also but it wont work here. Help me
Upvotes: 1
Views: 731
Reputation: 2317
As user2864740
has pointed out above, the problem is not with your rounding, but with displaying the value as a string. Try:
decimal temp = 345.0000m;
String.Format("{0:0.00}", temp)
Upvotes: 2
Reputation: 124804
I don't think you're showing your real code. The following will give a result of 0, because (5 / 100) is evaluated using integer arithmetic:
decimal temp = 6900 * (5 / 100);
Console.WriteLine(temp.ToString()); // result is 0
If you use decimal, you will get the following:
decimal temp = 6900 * (5M / 100);
Console.WriteLine(temp.ToString()); // result is 345.00
However the decimal type does preserve trailing zeroes:
decimal temp = 6900 * (5.0000M / 100);
Console.WriteLine(temp.ToString()); // result is 345.0000
Preserving trailing zeroes like this was introduced in .NET 1.1 for more strict conformance with the ECMA CLI specification.
But there's nothing to stop you formatting the output with two decimals, e.g.:
decimal temp = 6900 * (5.0000M / 100);
Console.WriteLine(temp.ToString("N2")); // result is 345.00
Upvotes: 3
Reputation: 98868
I think you showing us wrong code because this doesn't get 345.00
or 345.0000
as a result. It always gets 0
.
Your temp
should be 0
because since you doing integer division, your 5 / 100
is always 0
. That's why your temp
will 6900 * 0
then it will be 0
.
If you show us the right code, your problem looks like showing problem instead of rounding problem.
If you want to format your number as a string, take a look at;
Upvotes: 1