-1

Below code gives me about 14 decimal places. How can i trim it to the 2 decimal place?

public class BigDecimalGenerator
     {     public static void main(String[] args)
    
     {  BigDecimal max = new BigDecimal("50.00");   
        BigDecimal min = new BigDecimal("-50.00");  
        BigDecimal range = max.subtract(min);   
        BigDecimal result = min.add(range.multiply(new BigDecimal(Math.random())));  
        System.out.println(result);     }
     }
Sam1977
  • 15
  • 4

2 Answers2

1

Use this method on BigDecimal

setScale(int newScale, int roundingMode)

using the desired scale (2) and roundingmode.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
1

Set the rounding mode and scale.

BigDecimal max = new BigDecimal("50.00");
BigDecimal min = new BigDecimal("-50.00");
BigDecimal range = max.subtract(min);
BigDecimal result = min
        .add(range.multiply(new BigDecimal(Math.random())));

result = result.setScale(2,RoundingMode.HALF_UP);

System.out.println(result);

Prints something like.

-31.28
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
WJS
  • 36,363
  • 4
  • 24
  • 39