How to display a number with always 2 decimal points using BigDecimal?

后端 未结 6 1337
北荒
北荒 2020-12-06 04:00

I am using BigDecimal to get some price values. Requirement is something like this, what ever the value we fetch from database, the displayed valued should have 2 d

相关标签:
6条回答
  • 2020-12-06 04:27

    To format numbers in JAVA you can use:

     System.out.printf("%1$.2f", d);
    

    where d is your variable or number

    or

     DecimalFormat f = new DecimalFormat("##.00");  // this will helps you to always keeps in two decimal places
     System.out.println(f.format(d)); 
    
    0 讨论(0)
  • 2020-12-06 04:32

    you can use the round up format

    BigDecimal bd = new BigDecimal(2.22222);
    System.out.println(bd.setScale(2,BigDecimal.ROUND_UP));
    

    Hope this help you.

    0 讨论(0)
  • 2020-12-06 04:33

    You need to use something like NumberFormat with appropriate locale to format

    NumberFormat.getCurrencyInstance().format(bigDecimal);
    
    0 讨论(0)
  • 2020-12-06 04:33

    BigDecimal.setScale would work.

    0 讨论(0)
  • 2020-12-06 04:50

    The below code may help.

    protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
        final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
        numberFormat.setGroupingUsed(true);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMinimumFractionDigits(2);
        return numberFormat.format(input);
    }
    
    0 讨论(0)
  • 2020-12-06 04:54

    BigDecimal is immutable, any operation on it including setScale(2, BigDecimal.ROUND_HALF_UP) produces a new BigDecimal. Correct code should be

            BigDecimal bd = new BigDecimal(1);
    //      bd.setScale(2, BigDecimal.ROUND_HALF_UP);   bd.setScale does not change bd
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            System.out.println(bd);
    

    output

    1.00
    
    0 讨论(0)
提交回复
热议问题