TYPE CONVERSIONS INT to STRING
INT to DOUBLE Java automatically supports the conversion from a
double variable to an integer. So no
special work is needed.
In the above code, d will get
the value of 4.0. DOUBLE
to INT (via rounding) One approach to converting a
double variable to an integer is to use rounding. There is a round function in the Math class
but note that it returns a long variable.
So we do need to typecast to an integer.
In the above code, the variable i would get the value of 4. DOUBLE
to INT (via truncation) We can convert a double to an int by omitting any decimal values all together. This is called truncation and can be done
using a simple typecast.
In the above code, the variable i would
get the value of 7. DOUBLE to DOUBLE with specified
precision Ok,
so this isn’t a type conversion. We
start with a double and we want another double that has a set number of
decimal places. But it is a form of
conversion that could be time consuming to figure out without a hint so we
will cover it here. Let’s
say we have the number 3.14159265 and we want it with two decimal points
only.
The above code will store the value 3.14 in d2. And, to get the same number to four decimal places, we use 10000 instead of 100. See below:
The above code will store the value 3.1416 in d2.
Here is an example:
The above code will output the following to screen: [2, 5, 8, 3] If you wish to get rid the of
the brackets, the following line would create a second String s2 without them:
Furthermore, if we wanted to
remove the commas and the spaces, we could use the replaceAll
method for Strings. The following line
creates a String named s3 that has no spaces or commas:
|