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
you can use a BigDecimal
To calculate with with BigDeciamls this class provides special methods that are used instead of the standard operators e.g. + - * / ...
that you from int, double and so on...
Depends on the range of your input. Many times, you can just use int or long. For money, just store the integer number of pennies. int will handle up to $20,000,000.00 which is large enough for my bank account. long goes far higher.
If your range is suitable, using long is much faster and cleaner than using BigDecimal
Yes, you can use an arbitrary precision class such as BigDecimal.
Yes: the java.math.BigDecimal class.
Use BigDecimal it offers much better precision