quick question.
Would this always be true?
int i = ...;
double d = i;
if (i == (int) d) ...
Or I need to do rounding to be sure?
if (i == Math.round(d)) ...
Since double is bigger data type than int, you can simply downcast double to int in Java. double is 64-bit primitive value and when you cast it to a 32-bit integer, anything after the decimal point is lost.
We can convert int to double in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly. It is also known as implicit type casting or type promotion.
double c = a; Here, the int type variable is automatically converted into double . It is because double is a higher data type (data type with larger size) and int is a lower data type (data type with smaller size). Hence, there will be no loss in data while converting from int to double .
Using Math. Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.
Yes, all possible int
values can round-trip to a double
safely.
You can verify it with this code:
for (int i = Integer.MIN_VALUE; ; i++) {
double d = i;
if (i != (int) d) {
throw new IllegalStateException("i can't be converted to double and back: " + i);
}
if (i == Integer.MAX_VALUE) {
break;
}
}
Note that I'm not using a normal for
loop, because it would either skip Integer.MAX_VALUE
or loop indefinitely.
Note that the same is not true for int
/float
or for long
/double
!
If you're on a slow computer or don't have time to run the loop to check for yourself, the relevant part of the Java Language Specification is here § 5.1.2 Widening Conversions:
The following 19 specific conversions on primitive types are called the widening primitive conversions:
- byte to short, int, long, float, or double
- short to int, long, float, or double
- char to int, long, float, or double
- int to long, float, or double
- long to float or double
- float to double
Widening primitive conversions do not lose information about the overall magnitude of a numeric value. Indeed, conversions widening from an integral type to another integral type and from float to double do not lose any information at all; the numeric value is preserved exactly. [...]
(The following section § 5.1.3 Narrowing Primitive Conversions ensures that the way back, double -> int, doesn't loose any information either.)
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