Search code examples
javabigdecimal

BigDecimal values wants set a new scale


I have a BigDecimal value, for example

BigDecimal bdVal = new BigDecimal("3.141592653");

I really want this value printed to be

dbVal: 3.141600000

What should I do for that ???


Solution

  • If you would like to round the value up to four decimal places, use

    BigDecimal rounded = bdVal.setScale(4, RoundingMode.HALF_UP);
    

    To print it with nine zeros, use this format:

    DecimalFormat decFormat = new DecimalFormat("0.000000000");
    String formatted = decFormat.format(rounded);
    

    Demo.