Closed dnadolny closed 11 years ago
Scala's own Double doesn't have it http://www.scala-lang.org/api/current/index.html#scala.Double$
Is there an idiomatic Scala way to parse a String to Double? If not, then java.lang.Double.valueOf(arg)
is the solution.
I think the idiomatic Scala way would be arg.toDouble
, using the implicit conversion to StringOps. StringOps.toDouble
delegates to java.lang.Double.parseDouble(arg)
, which returns a double primitive.
This is different behavior from java.lang.Double.valueOf(arg)
, which returns the equivalent of new Double(parseDouble(arg))
. You can see that by comparing (Java):
System.out.println(Double.valueOf("1.0") == Double.valueOf("1.0")); //false
System.out.println(Double.parseDouble("1.0") == Double.parseDouble("1.0")); //true
Since it's hard to get the Java behavior in Scala (you'd have to call valueOf, but worse than that is you would have to change all instances of == to eq to regain the reference equality check, which is only possible if you're converting all the code at once). I think the best solution is to make it arg.toDouble, and let this be a "gotcha" with conversion, if anyone was relying on the Java behavior.
Thanks for the suggestion. For now the solution is the same as https://github.com/mysema/scalagen/issues/54
Released in 0.3.1
Converting the Java
double a = Double.valueOf("1.0");
gives the scalaval a = "1.0"
. It should beval a = Double.valueOf("1.0")
.