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
?
round() The Math. round() function returns the value of a number rounded to the nearest integer.
When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With