How often you made an arithmetic operation using doubles and you end up with wrong values because of losing arithmetic precision?
I’m hoping that you would say NEVER, but in real worlds, from time to time we have this issue.
It is important to remember that Math.Round method can accept an extra parameter that can be used the direction of rounding when number is halfway between the:
Enjoy!
I’m hoping that you would say NEVER, but in real worlds, from time to time we have this issue.
double v1 = 0.7;
double v2 = 0.025;
double result = v1 / v2; (27. 999999999999996)
In this case you would expect to have 28 and not 27.99999…6. The simplest solution would be to use decimal and not double, but there are situation when this is not possible. In this cases I say different methods to rounds this value.It is important to remember that Math.Round method can accept an extra parameter that can be used the direction of rounding when number is halfway between the:
- AwayFromZero – The number is rounded toward the nearest number that is away from 0
- ToEven – The number is rounded toward the nearest even number
Math.Round(2.99, MidpointRounding.AwayFromZero); // 3
Math.Round(2.99, MidpointRounding.ToEven); // 3
Math.Round(6.5, MidpointRounding.AwayFromZero); // 7
Math.Round(6.5, MidpointRounding.ToEven); // 6
Enjoy!
That's why if somobody wants to use float and double for real stuff in an application should not miss the numerical analysis classes during college.. :-)
ReplyDelete