Search code examples
javanumbersprecisionsubtraction

Subtract and round double values by multiplier


I have two double values

double a = 1.07522;
double b = 1.0752;

and rounding multiplier value

public static final double ROUND_MULTIPLIER = 100000.0;

So there always should be 5 decimal places.

I need to subtract two double values and get result as a - b = 0.00002.

How can I do this with using ROUND_MULTIPLIER ?

I tried using BigDecimal as

BigDecimal.valueOf(a).subtract(BigDecimal.valueOf(b)).round(new MathContext((int)ROUND_MULTIPLIER)); 

but it not always works, sometimes return 2E-16, it returns weird value when try add to second value as below

BigDecimal.valueOf(a).subtract(BigDecimal.valueOf(b + 0.00002)).round(new MathContext((int)ROUND_MULTIPLIER));

I need to use ROUND_MULTIPLIER.


Solution

  • I don't understand why you must use ROUND_MULTIPLYER and what the exact reason of it's existance is, so I can only guess.

    Forcing the code to use ROUND_MULTIPLYER:

    public static final double ROUND_MULTIPLIER = 100000.0;
    
    public void foobar()
    {
        double a = 1.07522;
        double b = 1.0752;
    
        BigDecimal opA = BigDecimal.valueOf(a);
        BigDecimal opB = BigDecimal.valueOf(b);
    
        BigDecimal result = opA.subtract(opB);
    
        result = result.multiply(BigDecimal.valueOf(ROUND_MULTIPLIER));
    
        int cutResult = result.intValue();
    
        result = BigDecimal.valueOf(cutResult / ROUND_MULTIPLIER);
    
        System.out.println(result);
    }
    

    The output of this is

     0.000020
    

    Is that what you want? The code is definitly object to optimization, but I let that up to you to do ;-)