Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

float/double Math.Round in C# [duplicate]

Tags:

float ff = (float)31.15;  double dd = 31.15;  var frst = Math.Round(ff, 1, MidpointRounding.AwayFromZero);  var drst = Math.Round(dd, 1, MidpointRounding.AwayFromZero); 

frst: 31.1

drst: 31.2

Can someone explain why?

like image 963
Yaoqing Avatar asked Jan 17 '19 12:01

Yaoqing


People also ask

How does round () work in C?

The round( ) function in the C programming language provides the integer value that is nearest to the float, the double or long double type argument passed to it. If the decimal number is between “1 and. 5′′, it gives an integer number less than the argument.

Does INT round up or down in C?

So ( sizeof(int) + that remainder - one) is always >= sizeof(int). So it always rounds up.


1 Answers

Well, Math.Round wants double, not float, that's why

Math.Round(ff, 1, MidpointRounding.AwayFromZero); 

equals to

Math.Round((double)ff, 1, MidpointRounding.AwayFromZero); 

and if we inspect (double)ff value

Console.Write(((double)ff).ToString("R")); 

we'll see round up errors in action

31.149999618530273 

Finally, Math.Round(31.149999618530273, 1, MidpointRounding.AwayFromZero) == 31.1 as expected

like image 149
Dmitry Bychenko Avatar answered Oct 31 '22 10:10

Dmitry Bychenko