Java - Decimal Format.parse to return double value with specified number of decimal places

前端 未结 4 775
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 18:50

I want to be able to convert a string to a Double given a number of decimal places in a format string. So \"###,##0.000\" should give me a Double

4条回答
  •  佛祖请我去吃肉
    2020-12-09 19:39

    The restriction of decimal places in DecimalFormat is really meant for use in the format() method and doesn't have much effect in the parse() method.

    In order to get what you want you need this:

        try {
            // output current locale we are running under (this happens to be "nl_BE")
            System.out.println("Current Locale is " + Locale.getDefault().toString());
    
            // number in Central European Format with a format string specified in UK format
            String numberCE = "1,234567"; // 1.234567
            String formatUK = "###,##0.000";
    
            // do the format
            DecimalFormat formatterUK = new DecimalFormat(formatUK);
            Double valCEWithUKFormat = formatterUK.parse(numberCE).doubleValue();
    
            // first convert to UK format string
            String numberUK = formatterUK.format(valCEWithUKFormat);
            // now parse that string to a double
            valCEWithUKFormat = formatterUK.parse(numberUK).doubleValue();
    
            // I want the number to DPs in the format string!!!
            System.out.println("CE Value     " + numberCE + " in UK format (" + formatUK + ") is " + valCEWithUKFormat);
    
        } catch (ParseException ex) {
            System.out.println("Cannot parse number");
        }
    

    You first need to get the number as a UK format string and then parse that number, using the UK formatter. That will get you the result you're looking for. NB, this will round the number to 3 decimal places, not truncate.

    By the way, I'm slightly surprised that your UK formatter is able to parse the CE format number. You really should be parsing the original number with a CE format parser.

提交回复
热议问题