44

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

The following code shows my problem:

    String numberString = "2.105,88";

    NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
    try {
        Number parsed = nf.parse(numberString);
        BigDecimal bd1 = new BigDecimal(parsed.toString());
        System.out.println(bd1.toString());

        BigDecimal bd2 = new BigDecimal(parsed.doubleValue());
        System.out.println(bd2);

        BigDecimal bd3 = new BigDecimal(numberString);
        System.out.println(bd3);

    } catch (ParseException e) {
        e.printStackTrace();
    }

The outpout of this is

2105.88

2105.8800000000001091393642127513885498046875

Exception in thread "main" java.lang.NumberFormatException at java.math.BigDecimal.(Unknown Source) at java.math.BigDecimal.(Unknown Source) at test.BigDecimalTest.main(BigDecimalTest.java:22)

The first output is correct, but it doesn't really make sense to convert a String to a Number (Double to be precise), then back to a String again and then into a specific type of Number, BigDecimal.

The second output is incorrect, but could be solved by setting the scale of the BigDecimal. However, the amount of digits is not always known.

The third output is obviously not what I'm looking for.

My question: What would be the best way? Are there better ways to do this?

2 Answers 2

45

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 formatted
        System.out.println(new BigDecimal(numberStringFixed));;     
        //direct but erroneous way if the string is not formatted
        System.out.println(new BigDecimal(numberString));;
        
    }
}

I hope this helps!

5
  • 15
    As for "properly formatted"... 2.105,88 is in fact entirely properly formatted in a bunch of locales... And in those locales, 2105.88 is not proper at all. What this whole ordeal would need is a Locale argument for the BigDecimal constructor...
    – ppeterka
    Oct 13, 2016 at 19:38
  • @ppeterka you're confusing presentation vs. logic when referring to "properly formatted". "2.105,88" isn't computer notation in any fashion. That's a presentation issue. It wouldn't make sense to make every conceivable mechanism for dealing with numbers require having a locale parameter purely to handle presentation. Dec 30, 2022 at 22:36
  • @NathanCrause I disagree. Converting something from and to a String always should require proper locale. You might not have encountered the issues that stem from the decimal character being different in various locals but it can break stuff in spectacular ways if not accounted for.
    – ppeterka
    Jan 1 at 2:59
  • @NathanCrause also curious: how would you solve the issue then, what should be the default locale?
    – ppeterka
    Jan 1 at 3:08
  • This way is not good, so if you pass "0.001" result will be 1
    – Mahdi
    Jul 26 at 5:50
33

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.

3
  • 1
    @JarettMillard In truth DecimalFormat have, NumberFormat have not this method
    – deFreitas
    Nov 24, 2016 at 17:37
  • @deFreitas NumberFormat is an abstract class. The docs for DecimalFormat explicitly tell you to create instances of it with NumberFormat.getInstance(). Nov 29, 2016 at 15:34
  • 2
    "NumberFormat is an abstract class" which doesn't have such method, meaning you have to cast back to DecimalFormat the result of the factory method.
    – Diego
    Dec 7, 2016 at 23:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.