more precise numeric datatype than double?

后端 未结 6 2075
南方客
南方客 2021-02-07 14:02

Is there a datatype in Java that stores a decimal number more precisely than a double?

6条回答
  •  自闭症患者
    2021-02-07 14:20

    Yes, use java.math.BigDecimal class. It can represent numbers with great precision.

    If you just need huge integers, you can use java.math.BigInteger instead.

    They both extend java.math.Number.

    You can even use your existing doubles if you need:

    double d = 67.67;
    BigDecimal bd = new BigDecimal(d);
    

    And you can get BigDecimal values out of databases with JDBC:

    ResultSet rs = st.executeQuery();
    while(rs.next()) {
        BigDecimal bd = rs.getBigDecimal("column_with_number");
    }
    

    Unfortunately, since Java does not support operator overloading, you can't use regular symbols for common mathematical operations like you would in C# and the decimal type.

    You will need to write code like this:

    BigDecimal d1 = new BigDecimal(67.67);
    BigDecimal d2 = new BigDecimal(67.68);
    BidDecimal d3 = d1.add(d2); // d1 + d2 is invalid
    

提交回复
热议问题