Best way to parseDouble with comma as decimal separator?

前端 未结 10 602
暗喜
暗喜 2020-11-22 06:14

Following is resulting in an Exception:

String p=\"1,234\";
Double d=Double.valueOf(p); 
System.out.println(d);

Is there a bet

相关标签:
10条回答
  • 2020-11-22 06:44

    You can use this (the French locale has , for decimal separator)

    NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
    nf.parse(p);
    

    Or you can use java.text.DecimalFormat and set the appropriate symbols:

    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator(',');
    symbols.setGroupingSeparator(' ');
    df.setDecimalFormatSymbols(symbols);
    df.parse(p);
    
    0 讨论(0)
  • 2020-11-22 06:45

    In the case where you don't know the locale of the string value received and it is not necessarily the same locale as the current default locale you can use this :

    private static double parseDouble(String price){
        String parsedStringDouble;
        if (price.contains(",") && price.contains(".")){
            int indexOfComma = price.indexOf(",");
            int indexOfDot = price.indexOf(".");
            String beforeDigitSeparator;
            String afterDigitSeparator;
            if (indexOfComma < indexOfDot){
                String[] splittedNumber = price.split("\\.");
                beforeDigitSeparator = splittedNumber[0];
                afterDigitSeparator = splittedNumber[1];
            }
            else {
                String[] splittedNumber = price.split(",");
                beforeDigitSeparator = splittedNumber[0];
                afterDigitSeparator = splittedNumber[1];
            }
            beforeDigitSeparator = beforeDigitSeparator.replace(",", "").replace(".", "");
            parsedStringDouble = beforeDigitSeparator+"."+afterDigitSeparator;
        }
        else {
            parsedStringDouble = price.replace(",", "");
        }
    
        return Double.parseDouble(parsedStringDouble);
    
    }
    

    It will return a double no matter what the locale of the string is. And no matter how many commas or points there are. So passing 1,000,000.54 will work so will 1.000.000,54 so you don't have to rely on the default locale for parsing the string anymore. The code isn't as optimized as it can be so any suggestions are welcome. I tried to test most of the cases to make sure it solves the problem but I am not sure it covers all. If you find a breaking value let me know.

    0 讨论(0)
  • 2020-11-22 06:47

    Use java.text.NumberFormat:

    NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
    Number number = format.parse("1,234");
    double d = number.doubleValue();
    

    Updated:

    To support multi-language apps use:

    NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
    
    0 讨论(0)
  • 2020-11-22 06:48

    You of course need to use the correct locale. This question will help.

    0 讨论(0)
  • 2020-11-22 06:56

    If you don't know the correct Locale and the string can have a thousand separator this could be a last resort:

        doubleStrIn = doubleStrIn.replaceAll("[^\\d,\\.]++", "");
        if (doubleStrIn.matches(".+\\.\\d+,\\d+$"))
            return Double.parseDouble(doubleStrIn.replaceAll("\\.", "").replaceAll(",", "."));
        if (doubleStrIn.matches(".+,\\d+\\.\\d+$"))
            return Double.parseDouble(doubleStrIn.replaceAll(",", ""));
        return Double.parseDouble(doubleStrIn.replaceAll(",", "."));
    

    Be aware: this will happily parse strings like "R 1 52.43,2" to "15243.2".

    0 讨论(0)
  • 2020-11-22 06:57

    As E-Riz points out, NumberFormat.parse(String) parse "1,23abc" as 1.23. To take the entire input we can use:

    public double parseDecimal(String input) throws ParseException{
      NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
      ParsePosition parsePosition = new ParsePosition(0);
      Number number = numberFormat.parse(input, parsePosition);
    
      if(parsePosition.getIndex() != input.length()){
        throw new ParseException("Invalid input", parsePosition.getIndex());
      }
    
      return number.doubleValue();
    }
    
    0 讨论(0)
提交回复
热议问题