Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast variable to int vs round() function

Tags:

c

int

rounding

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.

like image 219
cmp Avatar asked Jun 20 '12 21:06

cmp


People also ask

What is the difference between the round () function and the int () function?

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.

Does casting to int round up or down?

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.

Does int () always round down?

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.

What is round () function?

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.


1 Answers

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)

like image 113
Levon Avatar answered Oct 06 '22 02:10

Levon