如何查找 Scala 字符串是否可解析为 Double ? [英] How to find if a Scala String is parseable as a Double or not?

查看:70
本文介绍了如何查找 Scala 字符串是否可解析为 Double ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Scala 中有一个字符串,并且我想尝试从中解析一个双精度值.

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

我知道,我可以调用 toDouble 然后在失败时捕获 java num 格式异常,但是有没有更简洁的方法来做到这一点?例如,如果有一个返回 Option[Double]parseDouble 函数,这将是合格的.

I know that, I can just call toDouble and then catch the java num format exception if this fails, but is there a cleaner way to do this? For example if there was a parseDouble function that returned Option[Double] this would qualify.

如果它已经存在于标准库中,我不想把它放在我自己的代码中,而我只是在错误的地方寻找它.

I don't want to put this in my own code if it already exists in the standard library and I am just looking for it in the wrong place.

感谢您提供的任何帮助.

Thanks for any help you can provide.

推荐答案

对于 Scala 2.13+,请参阅下面 Xavier 的回答.显然现在有一个 toDoubleOption 方法.

For Scala 2.13+ see Xavier's answer below. Apparently there's a toDoubleOption method now.

对于旧版本:

def parseDouble(s: String) = try { Some(s.toDouble) } catch { case _ => None }

<小时>

花哨的版本(除了娱乐价值,不要这样做;多年前,我曾经写过这样的怪物时我还是个呆子青年):


Fancy version (edit: don't do this except for amusement value; I was a callow youth years ago when I used to write such monstrosities):

case class ParseOp[T](op: String => T)
implicit val popDouble = ParseOp[Double](_.toDouble)
implicit val popInt = ParseOp[Int](_.toInt)
// etc.
def parse[T: ParseOp](s: String) = try { Some(implicitly[ParseOp[T]].op(s)) } 
                                   catch {case _ => None}

scala> parse[Double]("1.23")
res13: Option[Double] = Some(1.23)

scala> parse[Int]("1.23")
res14: Option[Int] = None

scala> parse[Int]("1")
res15: Option[Int] = Some(1)

这篇关于如何查找 Scala 字符串是否可解析为 Double ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆