Search code examples
javabigdecimal

BigDecimal - how to do this calculation in Java


I have ..

target = targetmax / difficulty

targetmax = 26959535291011309493156476344723991336010898738574164086137773096960

difficulty = 14484.162361

target = 26959535291011309493156476344723991336010898738574164086137773096960 / 14484.162361

target = 1861311315012765306929610463010191006516769515973403833769533170

So I attempted this in Java as

    double difficulty = 14484.162361;

    String targetmaxStr = "26959535291011309493156476344723991336010898738574164086137773096960";

    BigDecimal targetmaxd = new BigDecimal(targetmaxStr);

    BigDecimal difficultyd = new BigDecimal(difficulty);

    BigDecimal targetd = targetmaxd.divide(difficultyd, MathContext.DECIMAL128); 

    System.out.println("target : " + targetD);

It prints

target : 1.861311315012765229690386592708552E+63

I am really expecting value:

target = 1861311315012765306929610463010191006516769515973403833769533170


Solution

  • You have three problems.

    First, use targetd.toPlainString()) to print the BigDecimal out avoiding scientific notation.

    Second, you are limiting your precision too much by using MathContext.DECIMAL128. Try something like new MathContext(200) instead.

    Third, as was debated in the comments, creating your BigDecimal from a double creates some precision issues. Create from a String instead to avoid those.

    Here it is all together:

    String targetmaxStr = "26959535291011309493156476344723991336010898738574164086137773096960";
    BigDecimal targetmaxd = new BigDecimal(targetmaxStr);
    BigDecimal difficultyd = new BigDecimal("14484.162361");
    BigDecimal targetd = targetmaxd.divide(difficultyd, new MathContext(200)); 
    System.out.println("target : " + targetd.toPlainString());
    

    Result:

    target : 1861311315012765306929610463010191006516769515973403833769533170.5181511669744807274464658288015444595719414139754270599065953124329244737606680298383048483144520034008751609022370030307892100271382756