java解析字符串到双精度/浮点抛出错误
我正在从UI中提取两个值,如1234、2456.00等作为字符串。当我试图将这个字符串解析为float时,1234正在变成1234.0,当我试图将其解析为double时,它的抛出错误。我怎样才能解决这个问题
我正在使用SeleniumWeb驱动程序和java。下面是我尝试过的几件事
double Val=Double.parseDouble("SOQ");
double Val=(long)Double.parseDouble("SOQ");``
你可以在下面搜索框中键入要查询的问题!
我正在从UI中提取两个值,如1234、2456.00等作为字符串。当我试图将这个字符串解析为float时,1234正在变成1234.0,当我试图将其解析为double时,它的抛出错误。我怎样才能解决这个问题
我正在使用SeleniumWeb驱动程序和java。下面是我尝试过的几件事
double Val=Double.parseDouble("SOQ");
double Val=(long)Double.parseDouble("SOQ");``
# 1 楼答案
要解析为Double的数字包含“,”和空格,因此在进行解析之前,需要先去掉它们
# 2 楼答案
问题是您无法将非数字输入解析为
Double
例如:
将导致错误
但以下是有效的:
# 3 楼答案
我想你在试图弄明白如何解析这些数字时有点搞混了。下面是一个概述:
此代码将打印出来:
Java将在命中
.
时停止对数字的“解析”,因为整数永远不能有.
,对于任何其他非数字值,如"ABC"
、"123$"
、"one"
,也是如此。。。人类可能能够将“123$”理解为一个数字,但Java不会对如何解释“$”做出任何假设此外:对于float或double,您可以提供一个普通整数或任何在某处带有
.
的字符,但除了.
之外,不允许使用其他字符(甚至不允许,
或;
,甚至不允许使用空格)编辑:
如果你有一个结尾有“零”的数字,这对人类来说可能看起来很好,也可以理解,但计算机不需要它们,因为省略零时数字在数学上仍然是正确的
e、 g.
"123.00"
与123
或123.000000
相同 这只是在再次打印或显示数字时格式化输出的问题(在这种情况下,数字将被转换回字符串)。您可以这样做:
你可以在
DecimalFormat
{a1}上找到一个概述例如,表示“这是一个数字,但前导零被省略”,0表示“这是一个数字,即使是零也不会被省略”
希望这有帮助
# 4 楼答案
第一个问题是
"SOQ"
不是一个数字其次,如果要使用
String
创建一个数字,可以使用parseDouble
并输入一个没有小数点的值。像这样:如果将值保存为
long
,则不必进行任何转换即可将其保存为双精度。这将编译并打印10.0
:最后,请阅读此Asking a good question