Java保留两位小数的几种做法

在平时做项目时,可能有这样的业务需求:页面或界面上展示的数据保留小数点后两位。 
为了达到这样的展示效果,本文列举了几个方法: 
1. 使用java.math.BigDecimal 
2. 使用java.text.DecimalFormat 
3. 使用java.text.NumberFormat 
4. 使用java.util.Formatter 
5. 使用String.format 

本文给出上述5种方法的简单实现。 
代码如下: 

    //使用BigDecimal,保留小数点后两位 
    public static String format1(double value) {  
        BigDecimal bd = new BigDecimal(value);  
        bd = bd.setScale(2, RoundingMode.HALF_UP);  
        return bd.toString();  
    }  

    //使用DecimalFormat,保留小数点后两位 
    public static String format2(double value) {  
        DecimalFormat df = new DecimalFormat("0.00");  
        df.setRoundingMode(RoundingMode.HALF_UP);  
        return df.format(value);  
    }  
  
    //使用NumberFormat,保留小数点后两位  
    public static String format3(double value) { 
        NumberFormat nf = NumberFormat.getNumberInstance();  
        nf.setMaximumFractionDigits(2);  
        //setMinimumFractionDigits设置成2,如果不这么做,那么当value的值是100.00的时候返回100 
//而不是100.00   
        nf.setMinimumFractionDigits(2);  
        nf.setRoundingMode(RoundingMode.HALF_UP);  
        //如果想输出的格式用逗号隔开,可以设置成true 
        nf.setGroupingUsed(false);  
        return nf.format(value);  
    }  
  
    //使用java.util.Formatter,保留小数点后两位   
    public static String format4(double value) {  
        //%.2f % 表示 小数点前任意位数 2 表示两位小数 格式后的结果为 f 表示浮点型         
        return new Formatter().format("%.2f", value).toString();  
    }  
  
    //使用String.format来实现.这个方法其实和format4是一样的 
    public static String format5(double value) {  
        return String.format("%.2f", value).toString();  
    }  

转载于:https://my.oschina.net/u/1380875/blog/798687

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值