Best way to convert Locale specific String to BigDecimal

孤街醉人 提交于 2019-11-28 06:17:59

It seems like there is no other way since java.Lang.Number doesn't have a method which returns a BigDecimal type. Anyway it makes sense because BigDecimal only accepts strings which are properly formatted not like ""2.105,88" but like "2105.88" Let me show your my code:

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class JavaMain {
    public static void main(String[] args) {
        String numberString = "2.105,88";
        //using casting
        try {
            DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.GERMAN);
            df.setParseBigDecimal(true);
            BigDecimal bd = (BigDecimal) df.parseObject(numberString);
            System.out.println(bd.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //your way short version
        NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
        try {
            BigDecimal bd1 = new BigDecimal(nf.parse(numberString).toString());
            System.out.println(bd1.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String numberStringFixed = "2105.88";
        //direct string formated
        System.out.println(new BigDecimal(numberStringFixed));;     
        //direct but erroneous way if the string is not formated
        System.out.println(new BigDecimal(numberString));;

    }
}

I hope this helps!

Jarett Millard

DecimalFormat has a method called setParseBigDecimal that causes parse() to return a BigDecimal. You just need to cast the returned Number.

The Problem is the formatting of your String. You should go with the 3rd Method, but format your String like this: String numberString = "2105.88";

You will be able to see this from the given examples here: Link to Java Api

Edit: Ok, so I see 2 possible solutions for this. Either go with your solution 1 (That's what I prefer) or do something like:

numberString = numberString.replaceAll(".", "");
numberString = numberString.replaceAll(",", ".");
BigDecimal bd3 = new BigDecimal(numberString);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!