简体   繁体   中英

Java, parse string to bigdecimal issue

I try to parse this String into a bigdecimal with comma replaced by a point.

String priceStr = "0,04";
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.US);
df.setParseBigDecimal(true);
df.setParseIntegerOnly(false);
BigDecimal price = null;
try {
        price = (BigDecimal) df.parseObject(priceStr);
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But i get an integer instead of a bigdecimal value(price = 4). Any idea?

0,04 is not a number formatted in the US locale.

If the value you expect to be parsed from that is 0.04 , you would need to use another locale which does use , as a decimal separator, eg Locale.FRANCE .

If you want to convert a non-US local decimal to a US local one you have to do two conversions, ie,

String priceStr = "0,04";
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
df.setParseBigDecimal(true);
df.setParseIntegerOnly(false);
BigDecimal price = null;
try {
    price = (BigDecimal) df.parseObject(priceStr);
} catch (ParseException e1) {
    e1.printStackTrace();
}
System.out.println(NumberFormat.getInstance(Locale.US).format(price));

how can i detect which locale is it from?

You simply check if the number String contains a . :

DecimalFormat df = (priceStr.contains(".")) ? 
                      (DecimalFormat) NumberFormat.getInstance(Locale.US) :
                      (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);

Try this :

String priceStr = "0,04";
DecimalFormatSymbols symbol=new DecimalFormatSymbols();
symbol.setDecimalSeparator(','); 
String Pattarn="#,##";
DecimalFormat df=new DecimalFormat(Pattarn, symbol);
df.setParseBigDecimal(true);

try {
    BigDecimal price = (BigDecimal) df.parse(priceStr);
} catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM