Convert a String to Double - Java

前端 未结 5 2046
慢半拍i
慢半拍i 2020-11-27 19:51

What is the easiest and correct way to convert a String number with commas (for example: 835,111.2) to a Double instance.

Thanks.

5条回答
  •  天涯浪人
    2020-11-27 20:00

    The easiest is not always the most correct. Here's the easiest:

    String s = "835,111.2";
    // NumberFormatException possible.
    Double d = Double.parseDouble(s.replaceAll(",",""));
    

    I haven't bothered with locales since you specifically stated you wanted commas replaced so I'm assuming you've already established yourself as a locale with comma is the thousands separator and the period is the decimal separator. There are better answers here if you want correct (in terms of internationalization) behavior.

提交回复
热议问题