Search code examples
javamathcontext

How to set scale for Math.Context in Java?


I'm using Math.Context in my coding. Now the problem is Math.Context is calculating everything after decimal. I want to define Scale of 8 (means 8 digits after decimal point) for Math.Context. Please note i'm not looking for precision. I know how to define precision. I need scale.

This is my Math.Context code line :

answer =  firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), MathContext.DECIMAL32);

Solution

  • You can do what you're asking. I show you how but before that i would like to tell you that you have to setScale() on BigDecimal. In this case I'm assuming that answer variable is BigDecimal . Here is your answer

    answer =  firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), MathContext.DECIMAL32);
    answer = answer.setScale(5, RoundingMode.HALF_EVEN); 
    // YOU CAN SET YOUR OWN DESIRED SCALE OR ROUNDINGMODE