在java中实现double的四舍五入保留指定位小数

方式一:

double f = 3.1516;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); 

输出结果f1为 3.15;
源码解读:
public BigDecimal setScale(int newScale, int roundingMode) //int newScale 为小数点后保留的位数, int roundingMode 为变量进行取舍的方式;
BigDecimal.ROUND_HALF_UP 属性含义为为四舍五入

方式二:

String format = new DecimalFormat("#.0000").format(3.1415926);
System.out.println(format);

输出结果为 3.1416
源码解读:
#.00 表示两位小数 #.0000四位小数 以此类推…

方式三:

double num = 3.1415926;
String result = String.format("%.4f", num);
System.out.println(result);

输出结果为:3.1416
源码解读:
%.2f 中 %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。

方式四:

double num = Math.round(5.2544555 * 100) * 0.01d;
System.out.println(num);

输出结果为:5.25
源码解读:
最后乘积的0.01d表示小数点后保留的位数(四舍五入),0.0001 为小数点后保留4位,以此类推…

方式五:

String.format("%.2f", d)

源码解读:
只是用于程序中的格式化数值然后输出

总结:

将程序中的double值精确到小数点后两位。可以四舍五入,也可以直接截断。
比如:输入12345.6789,输出可以是12345.68也可以是12345.67。至于是否需要四舍五入,可以通过参数来决定(RoundingMode.UP/RoundingMode.DOWN等参数)。

实现代码:

package com.clzhang.sample;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DoubleTest {
    /** 保留两位小数,四舍五入的一个老土的方法 */
    public static double formatDouble1(double d) {
        return (double)Math.round(d*100)/100;
    }
    public static double formatDouble2(double d) {
        // 旧方法,已经不再推荐使用
    // BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP);
        // 新方法,如果不需要四舍五入,可以使用RoundingMode.DOWN
        BigDecimal bg = new BigDecimal(d).setScale(2, RoundingMode.UP);
        return bg.doubleValue();
    }
    public static String formatDouble3(double d) {
        NumberFormat nf = NumberFormat.getNumberInstance();

        // 保留两位小数
        nf.setMaximumFractionDigits(2); 
        // 如果不需要四舍五入,可以使用RoundingMode.DOWN
        nf.setRoundingMode(RoundingMode.UP);
        return nf.format(d);
    }
    /**这个方法挺简单的 */
    public static String formatDouble4(double d) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(d);
    }
    /**如果只是用于程序中的格式化数值然后输出,那么这个方法还是挺方便的, 应该是这样使用:System.out.println(String.format("%.2f", d));*/
    public static String formatDouble5(double d) {
        return String.format("%.2f", d);
    }
    public static void main(String[] args) {
        double d = 12345.67890;
        System.out.println(formatDouble1(d));
        System.out.println(formatDouble2(d));
        System.out.println(formatDouble3(d));
        System.out.println(formatDouble4(d));
        System.out.println(formatDouble5(d));
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值