- Solid lines indicate conversions that will not lose precision in the numbers
- Dashed lines will lose some precision if converted.
So if you take int: 123456789 and you want to make it into a "Float" all you need to do is
- int n = 123456789
- float f = n
This will cause the final outcome to take 123456789 and turn it into 1.23456792E8 Notice everything is accurate up to seven?
Lastly a few rules to keep in mind:
- If either of the operands is of type double, the other one will be converted to a double.
- Otherwise, if either of the operands is of type float, the other one will be converted to a float.
- Otherwise, if either of the operands is of type long, the other one will be converted to a long.
- Otherwise both operands will convert to an int.
Java Casts:
As we learned in the above made section you can convert an integer to a double now it stands to reason that you might sometimes want to convert a double back to an integer. Java adds a thing called "Cast" into mix. Casts are used anytime you want to do a conversion that will result in loss of accuracy. The syntax for it is simple like so:
- double x = 9.9998
- int nx = (int) x;
This should print out: 9 as the result when nx is called in a print statement here is the proof:
No comments:
Post a Comment