杰瑞科技汇

Java float四舍五入怎么实现?

方法 类/包 返回类型 说明 适用场景
Math.round() java.lang.Math longint 标准四舍五入,.5 向上取整,返回整数类型。 需要将浮点数转换为最接近的整数时。
BigDecimal java.math.BigDecimal BigDecimal 提供高精度的四舍五入,可指定舍入模式(如 HALF_UP)。 金融、财务计算等对精度要求极高的场景。
String.format() java.lang.String String 通过格式化字符串来控制小数位数,内部使用 BigDecimal 需要将结果格式化为字符串并显示时(如保留两位小数)。
DecimalFormat java.text String String.format() 类似,是另一个格式化工具。 需要更复杂的数字格式化规则时。

Math.round() - 最常用的方法

这是最直接、最简单的四舍五入方法,它遵循“四舍五入”的数学规则。

Java float四舍五入怎么实现?-图1
(图片来源网络,侵删)

注意Math.round() 的返回值类型取决于传入参数的类型:

  • 如果传入 float,则返回 long
  • 如果传入 double,则返回 int

示例代码

public class FloatRounding {
    public static void main(String[] args) {
        float number1 = 3.4f;
        float number2 = 3.5f;
        float number3 = 3.6f;
        float number4 = -3.5f; // 负数情况
        // Math.round(float) 返回 long
        long rounded1 = Math.round(number1); // 3.4 -> 3
        long rounded2 = Math.round(number2); // 3.5 -> 4
        long rounded3 = Math.round(number3); // 3.6 -> 4
        long rounded4 = Math.round(number4); // -3.5 -> -4 (向绝对值大的方向舍入)
        System.out.println("原始值: " + number1 + ", 四舍五入后: " + rounded1);
        System.out.println("原始值: " + number2 + ", 四舍五入后: " + rounded2);
        System.out.println("原始值: " + number3 + ", 四舍五入后: " + rounded3);
        System.out.println("原始值: " + number4 + ", 四舍五入后: " + rounded4);
        // 如果想得到 int,可以先强制转换为 int,或者使用 Math.round(double)
        int intRounded = (int) Math.round(number2);
        System.out.println("使用 Math.round 后强制转为 int: " + intRounded);
    }
}

输出:

原始值: 3.4, 四舍五入后: 3
原始值: 3.5, 四舍五入后: 4
原始值: 3.6, 四舍五入后: 4
原始值: -3.5, 四舍五入后: -4
使用 Math.round 后强制转为 int: 4

BigDecimal - 精确控制的首选

对于金融或科学计算,floatdouble 的精度问题可能会导致错误。BigDecimal 提供了任意精度的十进制数表示,并且可以精确地控制舍入方式。

推荐做法:使用 String 构造 BigDecimal,而不是使用 doublefloat 构造,以避免浮点数本身的精度问题。

Java float四舍五入怎么实现?-图2
(图片来源网络,侵删)

示例代码

import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalRounding {
    public static void main(String[] args) {
        // 使用 String 构造 BigDecimal,避免浮点数精度问题
        BigDecimal number1 = new BigDecimal("3.451");
        BigDecimal number2 = new BigDecimal("3.456");
        BigDecimal number3 = new BigDecimal("3.450");
        // 保留两位小数,使用 HALF_UP 模式(标准的四舍五入)
        BigDecimal rounded1 = number1.setScale(2, RoundingMode.HALF_UP);
        BigDecimal rounded2 = number2.setScale(2, RoundingMode.HALF_UP);
        BigDecimal rounded3 = number3.setScale(2, RoundingMode.HALF_UP);
        System.out.println("原始值: " + number1 + ", 四舍五入后: " + rounded1); // 3.45
        System.out.println("原始值: " + number2 + ", 四舍五入后: " + rounded2); // 3.46
        System.out.println("原始值: " + number3 + ", 四舍五入后: " + rounded3); // 3.45
        // 也可以四舍五入到整数
        BigDecimal roundedToInt = number1.setScale(0, RoundingMode.HALF_UP);
        System.out.println("原始值: " + number1 + ", 四舍五入为整数: " + roundedToInt); // 3
        // 其他舍入模式示例
        BigDecimal roundedUp = number1.setScale(2, RoundingMode.UP);     // 远离零舍入 (3.46)
        BigDecimal roundedDown = number1.setScale(2, RoundingMode.DOWN); // 向零舍入 (3.45)
        System.out.println("使用 UP 模式: " + roundedUp);
        System.out.println("使用 DOWN 模式: " + roundedDown);
    }
}

输出:

原始值: 3.451, 四舍五入后: 3.45
原始值: 3.456, 四舍五入后: 3.46
原始值: 3.450, 四舍五入后: 3.45
原始值: 3.451, 四舍五入为整数: 3
使用 UP 模式: 3.46
使用 DOWN 模式: 3.45

String.format() - 用于格式化输出

当你需要将一个 float 格式化为特定小数位数的字符串时,String.format() 非常方便,它内部使用 BigDecimal 来保证精度。

示例代码

public class StringFormatRounding {
    public static void main(String[] args) {
        float price = 19.995f;
        // %.2f 表示保留两位小数,会自动进行四舍五入
        String formattedPrice = String.format("%.2f", price);
        System.out.println("原始值: " + price);
        System.out.println("格式化为两位小数: " + formattedPrice); // 输出 "20.00"
        float anotherPrice = 123.456f;
        String formattedAnother = String.format("%.1f", anotherPrice); // 保留一位小数
        System.out.println("原始值: " + anotherPrice);
        System.out.println("格式化为一位小数: " + formattedAnother); // 输出 "123.5"
    }
}

输出:

原始值: 19.995
格式化为两位小数: 20.00
原始值: 123.456
格式化为一位小数: 123.5

DecimalFormat - 另一个格式化工具

DecimalFormatjava.text 包中的一个类,功能与 String.format() 类似,但更面向对象,适合在需要复杂、可重用的格式化规则时使用。

示例代码

import java.text.DecimalFormat;
public class DecimalFormatRounding {
    public static void main(String[] args) {
        float number = 1234.5678f;
        // 创建一个模式,#.## 表示保留两位小数
        DecimalFormat df = new DecimalFormat("#.##");
        // 应用格式化
        String formattedNumber = df.format(number);
        System.out.println("原始值: " + number);
        System.out.println("使用 DecimalFormat 格式化: " + formattedNumber); // 输出 "1234.57"
        // 可以设置舍入模式
        df.setRoundingMode(java.math.RoundingMode.DOWN); // 改为向下舍入
        String formattedDown = df.format(number);
        System.out.println("使用 DOWN 模式格式化: " + formattedDown); // 输出 "1234.56"
    }
}

输出:

原始值: 1234.5678
使用 DecimalFormat 格式化: 1234.57
使用 DOWN 模式格式化: 1234.56

如何选择?

场景 推荐方法 理由
简单地将浮点数转为整数(如 3.6 -> 4) Math.round() 最简单、最高效。
金融、财务计算,或需要精确控制舍入模式 BigDecimal 精度最高,最可靠,是处理货币和科学计算的标准。
只需要将结果显示为固定小数位的字符串 String.format()DecimalFormat 代码简洁,专为格式化输出设计。
进行复杂的、可配置的数字格式化 DecimalFormat 面向对象,可以创建和重用格式化模式。

重要提醒:由于 floatdouble 本身是二进制浮点数,它们无法精确表示某些十进制小数(如 1),在涉及金钱等高精度场景时,应尽可能使用 BigDecimal 来进行所有计算,而不是先用 float 计算,最后再四舍五入。

分享:
扫描分享到社交APP
上一篇
下一篇