Best way to parseDouble with comma as decimal separator?

前端 未结 10 635
暗喜
暗喜 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: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.

提交回复
热议问题