Or (double) and Double.parseDouble? When to use which ?
I've been asking me this lately
Or (double) and Double.parseDouble? When to use which ?
I've been asking me this lately
Casting to an int and converting to an int, these are the questions you are trying to ask.
Integer.parseInt - used to convert a string to an Integer. Eg: int x = Integer.parseInt("44") assigns 44 to x. It will throw a number format exception if it fails to convert the string to an integer.
int x = (int) 3.142 - assigns 3 to the value x, meaning the compiler truncates the numbers after decimal point and assigns the value 3 to the variable x which is of type int. Here the precision of the double value will be lost.
Similarly you can use Double.parseDouble() to convert a String to a double.
Using casts like (double)
can convert one similar type to another similar type (any number to a double), Double.parseDouble()
is used to convert different types to a double
(I think it might just be String.class to double I could be wrong). If you want to convert a type to a Double
object you can use Double.valueOf()
, the difference is that Double.parseDouble()
returns the primitive type while Double.valueOf()
returns a new instance of Double.class
.
parseInt and parseDouble are used to convert a String to a double. This is not possible with a cast (i.e. (int)"123").
A cast is used to convert a variable of one type to a variable of another type. This post discusses what types can be cast to other types, including casting to int.