Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Math.Round return an int? [duplicate]

Tags:

c#

math

In C#, why don't the rounding math functions Floor, Ceiling and Round return an int? Considering the result of the function will always be an integer, why does it return a float, double or decimal?

like image 566
Robin Rodricks Avatar asked Feb 08 '13 05:02

Robin Rodricks


People also ask

What is the return data type of Math round?

round() The Math. round() function returns the value of a number rounded to the nearest integer.

Does casting a double to an int round up or down?

When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value.

Why does Math round round down?

5 to be rounded is rounded either up or down so that the result of the rounding is always an even number. Thus 2.5 rounds to 2.0, 3.5 to 4.0, 4.5 to 4.0, 5.5 to 6.0, and so on.

Why does Math floor return a double Java?

It's for precision. The double data-type has a 53 bit mantissa. Among other things that means that a double can represent all whole up to 2^53 without precision loss. If you store such a large number in an integer you will get an overflow.


1 Answers

double has the range of ±5.0 × 10−324 to ±1.7 × 10308 and long has the range of –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Unfortunately not all integral floating point values can be represented by an integer.

For example, 1e19 has already exceeded the range of a 64-bit signed integer.

(long)Math.Round(1e19) == -9223372036854775808L // WTF? 

While it is true that the single-argument overloads Math.Round(double) and Math.Round(decimal) will always return an integral value, these overloads still cannot return an integer value type.

If you know that the value passed to the function will return a value representable by an integer value type, you can cast it yourself. The library won't do that because it needs to consider the general case.

like image 139
Alvin Wong Avatar answered Sep 19 '22 06:09

Alvin Wong