As it was mentioned before BigDecimal
is good option if you need better precision with doubles.
There is nice way to do rounding with BigDecimal
s. Basically you have to specify scale of the BigDecimal
instance. Take a look at this sample code:
BigDecimal decimalOne = new BigDecimal(0.1950);
BigDecimal decimalTwo = decimalOne.setScale(2, BigDecimal.ROUND_HALF_DOWN);
BigDecimal decimalThree = decimalOne.setScale(4, BigDecimal.ROUND_HALF_DOWN);
System.out.println("decimalOne: " + decimalOne);
System.out.println("decimalTwo: " + decimalTwo);
System.out.println("decimalThree: " + decimalThree);
Java 7 would print something like this:
decimalOne: 0.195000000000000006661338147750939242541790008544921875
decimalTwo: 0.20
decimalThree: 0.1950
Please note that BigDecimal
instances are immutable and that's why you have to assign result of setScale
to new instance (decimalOne
will not be changed).
In many financial system double
s are not used to store currency information; long
type with specific precision is used instead e.g. for precision 2, value 100
would be 1.00
, 122
would be 1.22
etc. That approach simplifies and seeds up calculations but it is not good for all the systems. However for simplicity of that question I won't dive into that subject too much.