How to set scale for Math.Context in Java?

1.7k Views Asked by At

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);
2

There are 2 best solutions below

0
On BEST ANSWER

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
2
On

There is no argument in the constructor or helper method in MathContext class to set scale. you can try BigDecimal where scale can be given as

In divide argument the parameters can be passed as follows,

BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) i.e

firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), 4, RoundingMode.FLOOR);

Reference to MathContext javadoc: https://docs.oracle.com/javase/7/docs/api/java/math/MathContext.html