Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

more precise numeric datatype than double?

Tags:

java

types

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

like image 592
Bjørn Moholt Avatar asked Mar 04 '11 22:03

Bjørn Moholt


1 Answers

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
like image 76
Pablo Santa Cruz Avatar answered Sep 17 '22 18:09

Pablo Santa Cruz