四舍五入的几种方法

  • 四舍五入保留整数

通过使用+0.5后强制类型转换来实现

(int)(num1 + 0.5)
public class Main {
    static int sum = 0;
    public static void main(String[] args) {
        double num1 = 6.56468;
        double num2 = 2.185658;
        double num3 = 1.8232;
        double num4 = 1.9986778;
        //四舍五入且保留整数
        System.out.println((int)(num1 + 0.5));
        System.out.println((int)(num2 + 0.5));
        System.out.println((int)(num3 + 0.5));
        System.out.println((int)(num4 + 0.5));
    }

}
7
2
2
2
  •  四舍五入保留整数

rint(x):x取整为它最接近的整数,如果x与两个整数的距离相等,则返回其中为偶数的那一个。

round(x):返回Math.floor(x+0.5),即“四舍五入”值。

例:

rint(3.5) = 4

rint(4.5) = 4

round(4.5) = 4

round(4.4) = 4 

同时使用Math.round()函数来实现

public class Main {
    static int sum = 0;
    public static void main(String[] args) {
        double num1 = 6.56468;
        double num2 = 2.185658;
        double num3 = 1.8232;
        double num4 = 1.9986778;
        System.out.println(Math.round(num1));
        System.out.println(Math.round(num2));
        System.out.println(Math.round(num3));
        System.out.println(Math.round(num4));

    }

}
7
2
2
2
  • 四舍五入保留任意位数

DecimalFormat df=new DecimalFormat("0.000");

构建此类,来确定保留位数

public class Main {
    static int sum = 0;
    public static void main(String[] args) {
        double num1 = 6.56468;
        double num2 = 2.185658;
        double num3 = 1.8232;
        double num4 = 1.9986778;
        
        DecimalFormat df=new DecimalFormat("0.000");//表示位数
        System.out.println(df.format(num1));
        System.out.println(df.format(num2));
        System.out.println(df.format(num3));
        System.out.println(df.format(num4));
    }

}
6.565
2.186
1.823
1.999

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yoin.

感谢各位打赏!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值