Java-----四舍五入保留两位小数的方法

本文详细介绍五种在Java中保留小数点后特定位数的方法:使用System.out.printf(), String.format(), BigDecimal.setScale(), Math.round()及DecimalFormat,每种方法均有实例演示,帮助开发者精确控制浮点数的显示格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、System.out.printf();      (若想保留多位,只需将"%.2f"中的2改为想保留个数)

System.out.println("----------第一种使用Printf打印---------------");
        double a = 3.1456;
        System.out.printf("%.2f",a);

2、String.format(); (若想保留多位,只需将"%.2f"中的2改为想保留个数)

System.out.println("\n--------第二种使用String的format()方法-------");
        String s1 = String.format("%.2f", a);
        System.out.println(s1);

3、BigDecimal 中的setScale(2,BigDecimal.ROUND_HALF_UP) 方法 (若想保留多位,只需将参数"2"中的2改为想保留个数)

System.out.println("--------第三种使用BidDecimal的setScale()方法-");
        BigDecimal bigDecimal = new BigDecimal(a).setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(bigDecimal);

4、Math.round()方法(round实质是四舍五入取整,下面原理就是将小数所取位数之前都变为整数之后再除运算)

System.out.println("--------第四种使用Math的round()方法----------");
        double round = Math.round(a*100)/100.0;
        System.out.println(round);

5、DecimalFormat    (若想保留多位"#.##"小数点后面的#个数则代表保留小数个数)

System.out.println("--------第五种使用DecimalFormat--------------");
        DecimalFormat df = new DecimalFormat("#.##");
        String format = df.format(a);
        System.out.println(format);

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值