Tuesday, March 26, 2013

Java;Notes - 9.) Conversions between Numeric Types

This next part is better shown with a graph.

  • 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:
  1. double x = 9.9998
  2. int nx = (int) x; 
This should print out: 9 as the result when nx is called in a print statement here is the proof:

Rounding numbers up:
If you wish to round a double to its next best option the syntax for that is simple as well:

  1. double x = 9.9998
  2. int nxr = (int) Math.round(x); 
The following image shows the code and the output:

Well that is all I have for this round! Thanks for tuning in!