robbii15
robbii15

Reputation: 33

Math.Round(double,2) returns 1 decimal

Why does this code returns 1 decimal instead of 2

p = Math.Round(9431.796, 2);

If I replace this with p = Math.Round(9431.796, 4); It still returns 1 decimal

Upvotes: 0

Views: 975

Answers (4)

JLRishe
JLRishe

Reputation: 101680

If you round 9431.796 to two decimal places, you will get 9431.80.

Numerical data types don't store actual digits. They store a representation of a number. 9431.80 is exactly the same number as 9431.8, and there will be no distinction made between them when they are stored in a decimal or double variable.

So if you display 9431.80 without doing anything to format it a certain way, it will display as 9431.8. So the problem is with your understanding of how numbers are stored in numerical datatypes.

You create a string with a certain number of decimal places by using .ToString(). You don't need to use Math.Round() in this case. .ToString() will round it:

var p = 9431.796.ToString("0.00");
Console.WriteLine(p);                // 9431.80

Upvotes: 4

Rahul Nikate
Rahul Nikate

Reputation: 6337

You cannot because 9431.80 is equal to 9431.8. In this case however I guess that you want to print it out with specific format, which can be done like this:

string p = Math.Round(9431.796, 2).ToString("0.00");

Upvotes: 3

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

Since it rounds to 9431.80 it delete the last 0 which is useless. I would use :

int nbDec = 2;
p = Math.Round(9431.796, nbDec );
Console.Out.WriteLine(p.ToString("#,##0." + new string('#',nbDec ));

Which will display 9,431.80.

If you want more or less decimal, just change the nbDec value.

Upvotes: -1

pierroz
pierroz

Reputation: 7870

Math.Round(9431.796, 2) returns one decimal becauses it rounds to 9431.80. When displayed, it gets rid of the last 0, that's why you only see one decimal.
Math.Round(9431.796, 4) should definitely return 9431.796. Could you test it again?

Upvotes: -1

Related Questions