英文:
Conversion of String to BigDecimal format
问题
我有一个类似于"$1,234.00"的字符串。我需要将其转换为BigDecimal值。不能使用普通的BigDecimal转换方法,因为会抛出NumberFormatException异常。有没有一种方法可以实现这个?
英文:
I have a String which is like "$1,234.00". I need to convert it into a BigDecimal value. Cannot do it utilising normal BigDecimal conversion methods as it throws NumberFormatException. Is there a way it can be achieved?
答案1
得分: 1
"$1,234.00" 是一个格式化的数值文本,因此您需要使用NumberFormat来解析这个数字。
特别地,您需要一个DecimalFormat,这样您就可以调用setParseBigDecimal(true)方法,因为您希望得到一个BigDecimal作为结果,否则它可能会返回一个Double。
DecimalFormat format = new DecimalFormat("¤#,##0.00", DecimalFormatSymbols.getInstance(Locale.US));
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parse(input);
英文:
"$1,234.00" is a formatted numeric text, so you need to parse the number using a NumberFormat.
In particular, you need a DecimalFormat so you can call the setParseBigDecimal(true) method, since you want a BigDecimal as the result, otherwise it would likely have returned a Double.
DecimalFormat format = new DecimalFormat("¤#,##0.00", DecimalFormatSymbols.getInstance(Locale.US));
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parse(input);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论