将字符串转换为浮点数:java.lang.NumberFormatException,输入字符串为:”10.00″

huangapple go评论69阅读模式
英文:

Converting a String to Float : java.lang.numberformatexception for input string : "10.00"

问题

基本上我想要将浮点数价格(例如:20.0)变为20.00,多加一个零。所以我尝试在下面的代码中首先添加一个额外的零,这将把它转换为字符串,然后再将其转换回浮点数,因为我的对象类型需要将其存储为20.00作为浮点数。

Float lowest = productDetail1.getProductSummary().getPrice().getLowest();
String lowestPrice = String.format("$%.2f", lowest);
  try {
    Float floatVal = Float.valueOf(lowestPrice).floatValue();
    productDetail1.getProductSummary().getPrice().setLowest(floatVal);
  }catch (NumberFormatException e){
    LOGGER.error("Number Format Exception " + e.getMessage());
  }

所以我进行了调试,发现前两行代码运行良好,但是第3行出现错误:-

Float floatVal = Float.valueOf(lowestPrice).floatValue();

我得到的错误是:java.lang.NumberFormatException: For input string: "$10.00"

希望有人能够帮助我解决这个问题。一个书面的代码示例将作为解决方案很有帮助。

英文:

So basically i want my float number price (eg:- 20.0) to be 20.00, with an additional zero. So what i tried to do below here is first to add an extra zero, which results in converting it to a string and then convert it back to float because my object type needs to store it as 20.00 as a Float.

Float lowest = productDetail1.getProductSummary().getPrice().getLowest();
String lowestPrice = String.format("$%.2f", lowest);
  try {
    Float floatVal = Float.valueOf(lowestPrice).floatValue();
    productDetail1.getProductSummary().getPrice().setLowest(floatVal);
  }catch (NumberFormatException e){
    LOGGER.error("Number Format Exception " + e.getMessage());
  }

So i debugged it, and i found out that the first 2 lines of codes work fine, but an error is thrown at line 3 :-

Float floatVal = Float.valueOf(lowestPrice).floatValue();

The error im getting is :-
java.lang.numberformatexception for input string : "$10.00"

I hope someone can help me with this. A written code example will be helpful as a solution.

答案1

得分: 1

无法将 $ 解析为数字的一部分。在解析之前,您需要将其从字符串中移除。
例如:

Float floatVal = Float.valueOf(lowestPrice.substring(1)).floatValue();
英文:

It is not possible to parse $ as part of the number. You need to remove that from the String before parsing it.
For example

Float floatVal = Float.valueOf(lowestPrice.substring(1)).floatValue();

huangapple
  • 本文由 发表于 2020年10月20日 15:02:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64440039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定