I am trying to use BigDecimal to separate the decimal number into two parts (whole part and fractional part).
BigDecimal price1 = BigDecimal.valueOf(300.50);
BigDecimal price2 = BigDecimal.valueOf(300.05);
BigDecimal fractionalPart1 = price1.remainder(BigDecimal.ONE);
BigDecimal fractionalPart2 = price2.remainder(BigDecimal.ONE);
System.out.println(fractionalPart1.movePointRight(price1.scale()).abs().intValue()); // Output is 5
System.out.println(fractionalPart2.movePointRight(price2.scale()).abs().intValue()); // Output is 5
The output in both the above cases is 5. How to correct this (leaving the option of converting it into String) so it gives 50 and 5 correctly.
Okay, here is the solution.
By using valueOf and specifying the double value, the trailing zero is dropped. And this affects the scale. If you want to preserve the trailing zero, then you need to use the String constructor version of BigDecimal.
So change these
BigDecimal price1 = BigDecimal.valueOf(300.50);
BigDecimal price2 = BigDecimal.valueOf(300.05);
To these
BigDecimal price1 = new BigDecimal("300.50");
BigDecimal price2 = new BigDecimal("300.05");