You can use java.math.BigDecimal class for your solution.
The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion and hashing. It can handle very large and very small floating point numbers with great precision but compensating with the time complexity a bit.
A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale. If greater than or equal to zero, the scale is the number of digits to the right of the decimal point.strong text.
BigDecimal bigDecimal = new BigDecimal(num);
Java BigDecimal Methods
BigDecimal add(BigDecimal bigDecimal2)
BigInteger bigInt = new BigInteger("233233233233");
BigDecimal bigDecimal = new BigDecimal(bigInt);
BigDecimal bigDecimal2 = new BigDecimal(55662.3);
System.out.println(bigDecimal.add(bigDecimal2));
BigDecimal subtract(BigDecimal bigDecimal2):
bigDecimal.subtract(bigDecimal2)
You can use subtract method of BigDecimal class for you solution and easily compute difference between two BigDecimal number.
BigDecimal setScale(int newScale, RoundingMode roundingMode):
You can also set scale for numbers using setScale function.
UP: to round away from zero
CEILING: to round towards positive infinity
DOWN: to round towards zero
FLOOR: to round towards negative infinity
HALF_DOWN: to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round down
HALF_EVEN: to round towards the “nearest neighbor” unless both neighbors are equidistant, in which case, round towards the even neighbor
HALF_UP: to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round up
UNNECESSARY: to assert that the requested operation has an exact result, hence no rounding is necessary
BigDecimal bigDecimal = new BigDecimal("23323323.3533");
bigDecimal.setScale(2,RoundingMode.CEILING)
bigDecimal.setScale(2,RoundingMode.DOWN)
bigDecimal.setScale(2,RoundingMode.FLOOR)
Output:
23323323.3533
CEILING: 23323323.36
DOWN: 23323323.35
FLOOR: 23323323.35
Hope this will help.