Java large decimal format exception

Why does the following code throw a Java number format exception?

BigDecimal d = new BigDecimal("10934,375");

Solution

Yes, BigDecimal class does not consider any locale in its constructor. It needs a string, which can be read in the Javadoc of this constructor:

If you want to parse according to different locales and use commas as as decimal separators, you need to use Java. Net with specific locales text. DecimalFormat.

Example:

DecimalFormat fmt = new DecimalFormat("0.0",new DecimalFormatSymbols(Locale.GERMAN));
fmt.setParseBigDecimal(true);
BigDecimal n = (BigDecimal) fmt.parse("10934,375");

Note: you need to get an instance of decimalformat (a subclass of numberformat) so that you can call the setparsebigdecimal method Otherwise, it returns a double instead. It is a binary floating-point number. The binary floating-point number is cannot accurately represent many decimal fractions This will lead to the loss of accuracy in many cases

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>