Why doesn't Round return an integer?

result Double The rounded value. Although result is typed as a Double, it actually contains an integer value.


The Documentation for Round notes that it returns a Double although it contains an Integer.

This seems peculiar. Why don’t it just return an Integer?

2 Likes

Probably historical. Back before Int64 was a thing, Double was the largest integer you could represent, 54 bits. I have a lot of code that uses Double for integer values just for that reason. Double does not necesarily have to have a decimal component.

1 Like

Because the value you round can be outside the range of an integer.

Round basically adds 0.5 and then truncates the digits after the dot.

1 Like

And if it is used in an IF statement, you don’t have to worry about a “slight” difference as you might with a Double?

If a double contains an integer value, with no fractional component, the comparison is exact. It’s only when you have a fractional component that you encounter the slight difference.

1 Like

I believe this is only true for a subset of integers and the range for a double is about ± 2**53.

The reason? Floating point formats store data as two parts, the Mantissa and the Exponent, and each one has a fixed # of bits.

Explained here:

And this is why I understand Robert’s concern.
We have integers which are limited in size, and we have doubles, which are a problem for things like precision. Which data type would correspond to “an integer without limit”/“a double without decimal”? That would be the ideal type in this case.

1 Like

Because that’s a different function.

And it takes time to convert a double to an integer and then you’re likely to implicitly need to convert it back again if you’d used that result in an expression with any other double elements.

And you CAN use equality comparison of rounded doubles for any values less than 9007199254740993. The smallest positive integral value not representable by a 64bit IEEE double is 9007199254740993.