如何在java中将带有美元符号的字符串数值转换为BigDecimal?
我有一个字符串格式的美元金额。例如:字符串 salePrice = $348.00。
但是,我想将此 String 值转换为 BigDecimal 值,但它在字符串中有美元符号。我尝试了下面的代码,但它不起作用。
BigDecimal sPrice = new BigDecimal(salePrice);
我最终得到了下面这个异常:
java.lang.NumberFormatException
at java.math.BigDecimal.<init>(Unknown Source)
at java.math.BigDecimal.<init>(Unknown Source)
I have a dollar amount in a String format. For example: String salePrice = $348.00.
However, I want to convert this String value to a BigDecimal value, but it has a dollar sign in the string. I tried the code below but it isn't working.
BigDecimal sPrice = new BigDecimal(salePrice);
I ended up getting this exception below:
java.lang.NumberFormatException
at java.math.BigDecimal.<init>(Unknown Source)
at java.math.BigDecimal.<init>(Unknown Source)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
BigDecimal 构造函数 采用有效的数字字符串。
输出 =
348.00
您还可以查看 NumberFormat 类。使用此类,您可以设置相应的
Locale
。输出=
123.45
The BigDecimal Constructor take a valid numerical string.
Output =
348.00
You can also look at NumberFormat class. Using this class you can set your corresponding
Locale
.Output =
123.45
首先删除美元符号 ($)。
Remove the dollar sign ($) first.
构造函数要求字符串中有一个数字,您的字符串以
$
开头,这不是有效的数字。你需要先把它去掉。The constructor requires a Number in the string, your string starts with a
$
, which is not a valid number. You need to strip it out first.导入 java.text.DecimalFormat;
另请参阅:https:// /www.baeldung.com/java-decimalformat#basic-formatting
注意(!)
DecimalFormat
不是线程安全的,因此,在服务中,创建一个new
每次解析之前都会实例化。import java.text.DecimalFormat;
See also: https://www.baeldung.com/java-decimalformat#basic-formatting
NOTE (!)
DecimalFormat
is not thread-safe, so, in services, create anew
instance every time before parsing.