Java – a more precise numeric data type than double?

Is there a decimal number data type that is more accurate than double precision in Java?

Solution

Yes, use Java math. BigDecimal class It can well represent numbers

If you only need large integers, you can use Java math. BigInteger.

They all extend Java math. Number.

If necessary, you can even use the existing Doubles:

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

You can use JDBC to get BigDecimal values from the database:

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

Unfortunately, because Java does not support operator overloading, you cannot use regular symbols like common mathematical operations, as in c# and decimal types

You will need to write the following code:

BigDecimal d1 = new BigDecimal(67.67);
BigDecimal d2 = new BigDecimal(67.68);
BidDecimal d3 = d1.add(d2); // d1 + d2 is invalid
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>