Is there a datatype in Java that stores a decimal number more precisely than a double
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With