Convert a String to Double - Java

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

    Have a look at java.text.NumberFormat. For example:

    import java.text.*;
    import java.util.*;
    
    public class Test
    {
        // Just for the sake of a simple test program!
        public static void main(String[] args) throws Exception
        {
            NumberFormat format = NumberFormat.getInstance(Locale.US);
    
            Number number = format.parse("835,111.2");
            System.out.println(number); // or use number.doubleValue()
        }
    }
    

    Depending on what kind of quantity you're using though, you might want to parse to a BigDecimal instead. The easiest way of doing that is probably:

    BigDecimal value = new BigDecimal(str.replace(",", ""));
    

    or use a DecimalFormat with setParseBigDecimal(true):

    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
    format.setParseBigDecimal(true);
    BigDecimal number = (BigDecimal) format.parse("835,111.2");
    

提交回复
热议问题