我有一个字符串变量,需要将其解析为double
代码:
val myString = "9d"
myString.toDouble // produces "9.0" which i don't want. this should throws an error
如何使我的字符串按字面意义进行解释,以便产生异常?
答案 0 :(得分:3)
因此,显然,Java的java.lang.Double#parseDouble
能够解析各种字符串,例如NaN
,Infinity
等。
您的问题的答案似乎是 BigDecimal(myString).toDouble
出于好奇,这是三种不同的方法对各种输入字符串返回的结果:
def main(args: Array[String]): Unit = {
val strings = Seq("Infinity", "NaN", "9.0d", "9d", "9f", "9.0", "9.1", "1.4e14")
val parsers = Seq(
("Double", (s: String) => s.toDouble),
("BigDecimal", (s: String) => BigDecimal(s).toDouble),
("NumberFormat", (s: String) => NumberFormat.getNumberInstance.parse(s).doubleValue()),
)
for (string <- strings) {
println(s"\n------------- $string ------------")
for ((name, parser) <- parsers) {
val result = Try(parser(string)) match {
case scala.util.Success(value) => value
case scala.util.Failure(ex) => ex.toString
}
println(name.reverse.padTo(20, " ").reverse.mkString + " -> " + result)
}
}
}
结果:
------------- Infinity ------------
Double -> Infinity
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> java.text.ParseException: Unparseable number: "Infinity"
------------- NaN ------------
Double -> NaN
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> java.text.ParseException: Unparseable number: "NaN"
------------- 9.0d ------------
Double -> 9.0
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> 9.0
------------- 9d ------------
Double -> 9.0
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> 9.0
------------- 9f ------------
Double -> 9.0
BigDecimal -> java.lang.NumberFormatException
NumberFormat -> 9.0
------------- 9.0 ------------
Double -> 9.0
BigDecimal -> 9.0
NumberFormat -> 9.0
------------- 9.1 ------------
Double -> 9.1
BigDecimal -> 9.1
NumberFormat -> 9.1
------------- 1.4e14 ------------
Double -> 1.4E14
BigDecimal -> 1.4E14
NumberFormat -> 1.4
答案 1 :(得分:0)
我找到了scalaz
的解决方案:
import scalaz.Scalaz._
println("34b".parseDouble) // Failure(java.lang.NumberFormatException: For input string: "34b")
println("34.4".parseDouble) // Success(34.4)