How to find if a Scala String is parseable as a Double or not?

前端 未结 8 606
鱼传尺愫
鱼传尺愫 2020-12-24 01:49

Suppose that I have a string in scala and I want to try to parse a double out of it.

I know that, I can just call toDouble and then catch the java num

8条回答
  •  旧时难觅i
    2020-12-24 02:25

    There's nothing like this not only in Scala, but even in basic Java.

    Here's a piece code that does it without exceptions, though:

    def parseDouble(s: String)(implicit nf: NumberFormat) = {
        val pp = new ParsePosition(0)
        val d = nf.parse(s, pp)
        if (pp.getErrorIndex == -1) Some(d.doubleValue) else None
    }
    

    Usage:

    implicit val formatter = NumberFormat.getInstance(Locale.ENGLISH)
    
    Console println parseDouble("184.33")
    Console println parseDouble("hello, world")
    

提交回复
热议问题