Best way to parseDouble with comma as decimal separator?

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

提交回复
热议问题