Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a double equal to an integer always cast to that integer?

Will a double equal to an integer always cast to that integer (assuming the double is not one that causes an overflow). Example: Math.ceil() will return a double that is equal to an integer. Assuming no overflow, will it always cast to the same integer that it is supposedly equal to?

If not, how can I round up a double to an int or long?

like image 591
H2ONaCl Avatar asked Feb 17 '12 09:02

H2ONaCl


People also ask

Can integer be cast to double?

You cannot directly cast an Integer to a Double object. Also Double and Integer are immutable objects, so you cannot modify them in any way. Each numeric class has a primitive alternative ( Double vs double , Integer vs int , ...).

What happens when you cast a double to an int Java?

As we know double value can contain decimal digits (digits after decimal point), so when we convert double value with decimal digits to int value, the decimal digits are truncated.

What happens when you divide a double by an int in C++?

Because this is an int divided by a double, the compiler handles this by converting the int into a double. Thus, the result of b / d is a double. The next thing that C++ does is add a to the result of b / d . This is an int added to a double, so it converts the int to a double and adds, resulting in a double.


1 Answers

Since Java types are fixed and Java doubles have a 52 bit mantissa, they can (with ease) represent a 32-bit Java int without rounding.

like image 83
Joachim Isaksson Avatar answered Oct 08 '22 17:10

Joachim Isaksson