Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

后端 未结 5 543
情歌与酒
情歌与酒 2020-11-29 00:24

I have a BigDecimal number and i consider only 2 decimal places of it so i truncate it using:

bd = bd.setScale(2, BigDecimal.ROUND_DOWN)

No

相关标签:
5条回答
  • 2020-11-29 00:56

    If its money use:

    NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)
    
    0 讨论(0)
  • 2020-11-29 01:07
    new DecimalFormat("#0.##").format(bd)
    
    0 讨论(0)
  • 2020-11-29 01:19

    The below code may help you.

    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-11-29 01:20

    Use stripTrailingZeros().

    This article should help you.

    0 讨论(0)
  • 2020-11-29 01:23

    I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.

    The code is something like this:

    bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
    
    DecimalFormat df = new DecimalFormat();
    
    df.setMaximumFractionDigits(2);
    
    df.setMinimumFractionDigits(0);
    
    df.setGroupingUsed(false);
    
    String result = df.format(bd);
    
    0 讨论(0)
提交回复
热议问题