【问题标题】:Format decimal number after conversion from Integer从整数转换后格式化十进制数
【发布时间】:2017-06-23 11:14:00
【问题描述】:

我需要将整数转换为十进制数,然后根据特定条件使用 2、3、4 或 5 位精度对其进行格式化。

所以我使用了这个代码:

public  NumberFormat decimalFormatter = new DecimalFormat("#,##0.00");
    public static NumberFormat decimalFormatter3 = new DecimalFormat("#,##0.000");
    public static NumberFormat decimalFormatter4 = new DecimalFormat("#,##0.0000");
    public static NumberFormat decimalFormatter5 = new DecimalFormat("#,##0.00000");
    public void run(Integer numeroDecimali, Articoli articoli){
        if(numeroDecimali == null || numeroDecimali == 2)
            super.setValueAt(articoli.getPrezzoTot()!=null ? 
                    decimalFormatter.format(articoli.getPrezzoTot()) : "", rowIndex, 7);
        else if(numeroDecimali == 3)
            super.setValueAt(articoli.getPrezzoTot()!=null ? 
                    decimalFormatter3.format(articoli.getPrezzoTot()) : "", rowIndex, 7);
        else if(numeroDecimali == 4)
            super.setValueAt(articoli.getPrezzoTot()!=null ? 
                    decimalFormatter4.format(articoli.getPrezzoTot()) : "", rowIndex, 7);
        else if(numeroDecimali == 5)
            super.setValueAt(articoli.getPrezzoTot()!=null ? 
                    decimalFormatter5.format(articoli.getPrezzoTot()) : "", rowIndex, 7);

我输入了小数位数,并且使用 decimalFormat(2,3,4,5) 我可以格式化文本。 此代码有效,但是,有没有办法在没有这么多 IF 语句的情况下完成此操作?有没有办法结合numeroDecimali的信息来优化代码?

【问题讨论】:

标签: java decimalformat


【解决方案1】:

你可以使用这样的东西:

String.format( "%,." + numeroDecimali + "f", articoli.getPrezzoTot() );

只需确保numeroDecimali 具有有效值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-17
    • 2010-10-16
    • 2014-04-16
    • 2013-08-22
    • 2012-11-01
    相关资源
    最近更新 更多