Question

First I noticed that Math.Round() doesn't round for 2 digits as I as for:

double dd = Math.Round(1.66666, 2);

Result:

dd = 1.6699999570846558;

and then I created a new project with same .NET framework and the result is 1.67 now as it should been in the first place.

I've never seen Round behaving like this before, what is causing this problem?

Was it helpful?

Solution

Like the other comments mentioned, use decimal to hold the returned value:

decimal dd = Math.Round(1.66666M, 2);

The issue you described has nothing to do with the Round() function. You can read a bit about how the floating point numbers & fixed point numbers work, but the short explanation is:

With floating point variables (e.g. double), you cannot guarantee the precision of the number you save it them. So when you save something like 1.67 in a variable of the type double and then you check the value later on, therer is no guarantee you will get exactly 1.67. You may get a value like 1.66999999 (similar to what you got) or like 1.6700000001.

Fixed point variables (e.g. decimal) on the other hand, will give you that precision, so if you save 1.67, you will always get 1.67 back.

Please note that the Round() function returns the same type that you pass to it, so to make return a decimal, you need to pass it 1.66666M which is a decimal value rather than 1.66666 which is a floating point number.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top