java的四舍五入操作

本文介绍Java中两种常用的四舍五入方法:Math类round()函数与BigDecimal类divide()方法。前者简单但需注意负数处理;后者更为精确,支持自定义小数位数。

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

java 中的四舍五入操作

本文主要总结在java中常用到的两种四舍五入方法。
方法一使用简单,但是缺点在于需要注意负数时的进位模式,并且只能将小数进位为long型整数。
方法二较为复杂,但是可以在开发后当工具使用。好处在于:保留指定位数小数并且正数和负数在进位时规则保持一致。

  1. 在java.lang.Math类中定义一个用于四舍五入操作的方法: publicstaticlonground(doublea),但是使用该方法需要注意一点:如果是负数进行四舍五入,其小数位的数值如果$\color{red}{小于等于5}不会进位,大于5才会进位。代码示例如下:
import java.lang.Math;
public class TestDemo
{
    public static void main(String [] args)
    {
        double a = 16.50;
        double b = 16.51;
        double c = -16.50;
        double d = -16.51;
        System.out.println(Math.round(a));
        System.out.println(Math.round(b));
        System.out.println(Math.round(c));
        System.out.println(Math.round(d));
    }
}

程序执行结果
17
17
-16
-17
通过程序执行结果,在使用round()方法进行四舍五入操作时,应注意都到这一点。
2. 使用BigDecimal类实现准确的四舍五入操作
BigDecimal类表示的是大小数操作类。要使用BigDecimal类完成准确的四舍五入运算,需要用到该类中的定义的如下常量和方法:

常量或方法类型描述
public static int ROUND_HALF_UP常量向上进位
public BigDecimal(double val)构造函数传递一个double型数据
public BigDecimal divvide(BigDecimal divisor, int scale, int roundingMode)普通函数除法操作,设置保留小数位数及进位模式

代码示例如下:

import java.math.BigDecimal;
class MyMath
{
    /**
     * @param num 进行四舍五入操作的小数
     * @param scale 指定保留小数位数
     */
    public static double round(double num, int scale)
    {
        BigDecimal big = new BigDecimal(num);
        BigDecimal result = big.divide(new BigDecimal(1), scale, BigDecimal.ROUND_HALF_UP);
        // 将BigDecimal型数据转换成double型数据并返回
        return result.doubleValue();
    }
}
public class TestDemo
{
    public static void main(String [] args)
    {
        double a = 16.5500;
        double b = 16.5510;
        double c = -16.5500;
        double d = -16.5510;
        System.out.println(MyMath.round(a, 1));
        System.out.println(MyMath.round(b, 1));
        System.out.println(MyMath.round(c, 1));
        System.out.println(MyMath.round(d, 1));

    }
}

程序运行结果:
16.6
16.6
-16.6
-16.6

可以将MyMath类写成一个单独文件,并打包jar包,包所在路径加入CLASSPARH中,即可当成工具使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值