无法在 Scala 中将字符串转换为 long
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/41215421/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot convert string to a long in scala
提问by Programmerr
Why can I not convert the following string into a long? i am trying to do this in scala.
为什么我不能将以下字符串转换为长字符串?我想在 Scala 中做到这一点。
var a = "153978017952566571852"
val b = a.toLong  
when I try to convert it I get the NumberFormatException
当我尝试转换它时,我得到 NumberFormatException
回答by Psidom
Because the number exceeds the limit of Long Integer which goes from -9223372036854775808 to 9223372036854775807, with maximum of 19 digits, while your string contains 21 digits.
因为数字超过了 Long Integer 的限制,从-9223372036854775808 到 9223372036854775807,最多 19 位,而您的字符串包含 21 位。
You can convert it to Floator Doubleif you don't have to be exact:
如果您不必精确,您可以将其转换为Float或Double:
scala> val b = a.toFloat
b: Float = 1.5397802E20
scala> val b = a.toDouble
b: Double = 1.5397801795256658E20

