It sounds like you want arbitrary precision on the actual value (as opposed to just output). double
doesn't give you that. BigDecimal
does though. Its BigDecimal(String)
constructor sets the value and the scale (number of places to the right of the decimal) from a string, so:
BigDecimal d = new BigDecimal("1.10900");
BigDecimal
then gives you various math operations to stay within that scale, with various rounding options.
If at some point you need to get the double
value of the BigDecimal
, you can use its doubleValue
method. But note that at that point, again, you don't have a fixed number of places to the right of the decimal anymore.
Here's an example contrasting BigDecimal
and double
(Live Copy):
import java.math.*;
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
BigDecimal bd = new BigDecimal("1.10900");
bd = bd.divide(new BigDecimal("27"), BigDecimal.ROUND_HALF_DOWN);
System.out.println("1.109 / 27 using BigDecimal to five places: " + bd);
double d = 1.109;
d = d / 27.0;
System.out.println("1.109 / 27 using double: " + d);
}
}
Output:
1.109 / 27 using BigDecimal to five places: 0.04107
1.109 / 27 using double: 0.041074074074074075