Search code examples
javamathbigdecimal

Difference of BigDecimal as int?


I have two numbers, 1.4350 and 1.4300. When I subtract them, instead of returning 0.0050, I'm looking to get 50. It also needs to work with 90.25 and 90.10, returning 15.


Solution

  • You can use BigDecimal.unscaledValue(). This will return what you want as a BigInteger.

    // Two example numbers:
    BigDecimal val0 = new BigDecimal("1.4350");
    BigDecimal val1 = new BigDecimal("1.4300");
    
    
    // This might be a method:
    
    if (val0.scale() != val1.scale())
        throws new IllegalArgumentException("Scales are not the same!");
    
    BigDecimal subtr = val0.subtract(val1);
    System.out.println(subtr); // Prints 0.0050
    
    BigInteger unscaled = subtr.unscaledValue();
    System.out.println(unscaled); // Prints 50