Convert a String to Double - Java

前端 未结 5 2041
慢半拍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

    A link can say more than thousand words

    // Format for CANADA locale
    Locale locale = Locale.CANADA;
    String string = NumberFormat.getNumberInstance(locale).format(-1234.56);  // -1,234.56
    
    // Format for GERMAN locale
    locale = Locale.GERMAN;
    string = NumberFormat.getNumberInstance(locale).format(-1234.56);   // -1.234,56
    
    // Format for the default locale
    string = NumberFormat.getNumberInstance().format(-1234.56);
    
    
    // Parse a GERMAN number
    try {
        Number number = NumberFormat.getNumberInstance(locale.GERMAN).parse("-1.234,56");
        if (number instanceof Long) {
            // Long value
        } else {
            // Double value
        }
    } catch (ParseException e) {
    }
    

提交回复
热议问题