Best way to convert Locale specific String to BigDecimal

前端 未结 3 1120
耶瑟儿~
耶瑟儿~ 2020-12-05 02:04

I have to convert a German locale formatted String to a BigDecimal. However, I\'m struggling with the best solution.

The following code sho

3条回答
  •  遥遥无期
    2020-12-05 02:55

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

        String numberString = "2.105,88";
    
        NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
        if (nf instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat) nf;
            df.setParseBigDecimal(true);
            BigDecimal parsed = (BigDecimal) df.parse(numberString);
    
            System.out.println(parsed);
        }
    

    Output:

    2105.88

    setParseBigDecimal was introduced in Java 1.5.

提交回复
热议问题