I have seen it in several places where (int)someValue
has been inaccurate and instead the problem called for the round()
function. What is the difference between the two?
Specifically, if need be, for C99 C. I have also seen the same issue in my programs when writing them in java.
round(n) is a function to round a float, int(n) will cast a float to an integer and will get rid of the decimal part by truncating it.
It does not round, it just returns the integral part before the decimal point. Reference (thanks Rawling) Explicit Numeric Conversions Table: When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value.
However, INT actually is more sophisticated than that. INT rounds a number down using the Order rounding method. That is, it rounds a positive number down, towards zero, and a negative number down, away from zero. Therefore, it's easy to use INT to round a number up using the Math method.
The ROUND function rounds a number to a specified number of digits. For example, if cell A1 contains 23.7825, and you want to round that value to two decimal places, you can use the following formula: =ROUND(A1, 2) The result of this function is 23.78.
In case of casting a float
/double
value to int
, you generally loose the fractional part due to integer truncation.
This is quite different from rounding as we would usually expect, so for instance 2.8 ends up as 2 with integer truncation, just as 2.1 would end up as 2.
Update:
Another source of potential (gross) inaccuracy with casting is due to the limited range of values being able to be represented with integers as opposed to with floating point types (thanks to @R reminding us about this in the comment below)
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