-1

Or (double) and Double.parseDouble? When to use which ?

I've been asking me this lately

3 Answers3

2

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.

Ishaan
  • 67
  • 4
1

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.

vandench
  • 1,973
  • 3
  • 19
  • 28
  • Would like to note that converting to a String is somewhat different, you could do `"" + ((int) x)` or `String.valueOf()` or `Object.toString()` – vandench Oct 21 '16 at 23:52
1

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.

Community
  • 1
  • 1
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31