Search code examples
javadoublebigdecimal

How to get from 10.0/3*3 BigDecimal and double?


double a = 10.0;
double b =3; 
double c = a/b;
System.out.println(c*b);//answer = 10.0

BigDecimal bigDecimal1 = BigDecimal.valueOf(c);
BigDecimal bigDecimal2 = new BigDecimal("3");
System.out.println(bigDecimal1.multiply(bigDecimal2));//answer = 10.0000000000000005

I'm trying to make a calculator, but there's a problem with 10/3*3 I don't want to just calculate 10/3*3 this formula, I want to return this formula plus 0.2323232323232 of the float. So use the BigDecimal class. There's something wrong with it I couldn't get the exact result, that's what I wanted 10, Rather than get 10.0000000000000005


Solution

  • I believe your problem may be here

    double c = a/b;
    ...
    BigDecimal bigDecimal1 = BigDecimal.valueOf(c);
    

    You're expecting that a double can perfectly represent 10/3, and I doubt it can

    Maybe try something like this, which always represents numbers as BigDecimal

    new BigDecimal("10").divide(new BigDecimal("3"))
    

    At which point you'll notice that 10/3 is not representable as a decimal

    Non-terminating decimal expansion; no exact representable decimal result

    You need to decide how much precision you want, and then use rounding

    new BigDecimal("10")
        .setScale(10)
        .divide(new BigDecimal("3"), BigDecimal.ROUND_HALF_EVEN)
    

    Or you could use a rational number library, as suggested by Patricia. Perhaps see Is there a commonly used rational numbers library in Java?