杰瑞科技汇

Java如何四舍五入保留2位小数?

方法 1:使用 Math.round()(适用于基本数据类型)

Math.round() 会四舍五入到最接近的整数,如果要保留两位小数,可以先乘以 100,四舍五入后再除以 100。

Java如何四舍五入保留2位小数?-图1
(图片来源网络,侵删)
double num = 3.14159;
double roundedNum = Math.round(num * 100) / 100.0;
System.out.println(roundedNum); // 输出: 3.14

注意

  • 这种方法返回的是 double,但可能会出现浮点数精度问题(如 675 可能会变成 67 而不是 68)。
  • 适用于简单场景,但不推荐用于高精度计算。

方法 2:使用 BigDecimal(推荐,避免精度问题)

BigDecimal 是 Java 中处理高精度浮点数运算的最佳选择,可以避免 double 的精度问题。

import java.math.BigDecimal;
import java.math.RoundingMode;
double num = 3.14159;
BigDecimal bd = new BigDecimal(num);
BigDecimal rounded = bd.setScale(2, RoundingMode.HALF_UP);
System.out.println(rounded.doubleValue()); // 输出: 3.14

说明

  • setScale(2, RoundingMode.HALF_UP) 表示保留 2 位小数,并使用四舍五入模式。
  • RoundingMode.HALF_UP 是标准的四舍五入(>=0.5 进位,否则舍去)。

方法 3:使用 String.format()(格式化输出)

如果只是想格式化输出(不改变实际数值),可以使用 String.format()DecimalFormat

Java如何四舍五入保留2位小数?-图2
(图片来源网络,侵删)

(1) 使用 String.format()

double num = 3.14159;
String formatted = String.format("%.2f", num);
System.out.println(formatted); // 输出: "3.14"

注意

  • 返回的是 String,不是 double,适用于显示或日志记录。

(2) 使用 DecimalFormat

import java.text.DecimalFormat;
double num = 3.14159;
DecimalFormat df = new DecimalFormat("#.00");
String formatted = df.format(num);
System.out.println(formatted); // 输出: "3.14"

说明

  • #.00 表示保留 2 位小数,不足时补 0(如 3 会变成 00)。
  • 返回的是 String,不改变原始数值。

方法 4:使用 printf(控制台输出)

如果直接在控制台打印,可以用 printf 格式化输出:

double num = 3.14159;
System.out.printf("%.2f%n", num); // 输出: 3.14

方法 适用场景 返回类型 是否避免精度问题
Math.round() 简单四舍五入 double ❌(可能不精确)
BigDecimal 高精度计算 BigDecimal ✅(推荐)
String.format() 格式化输出 String ❌(不改变数值)
DecimalFormat 格式化输出 String ❌(不改变数值)

推荐

Java如何四舍五入保留2位小数?-图3
(图片来源网络,侵删)
  • 如果需要精确计算(如金融、货币),使用 BigDecimal
  • 如果只是格式化显示,使用 String.format()DecimalFormat

示例代码(完整版)

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class RoundingExample {
    public static void main(String[] args) {
        double num = 3.14159;
        // 1. Math.round()
        double rounded1 = Math.round(num * 100) / 100.0;
        System.out.println("Math.round(): " + rounded1); // 3.14
        // 2. BigDecimal (推荐)
        BigDecimal bd = new BigDecimal(num);
        BigDecimal rounded2 = bd.setScale(2, RoundingMode.HALF_UP);
        System.out.println("BigDecimal: " + rounded2); // 3.14
        // 3. String.format()
        String formatted1 = String.format("%.2f", num);
        System.out.println("String.format(): " + formatted1); // "3.14"
        // 4. DecimalFormat
        DecimalFormat df = new DecimalFormat("#.00");
        String formatted2 = df.format(num);
        System.out.println("DecimalFormat: " + formatted2); // "3.14"
        // 5. printf
        System.out.printf("printf: %.2f%n", num); // 3.14
    }
}

希望这能帮到你!如果有其他问题,欢迎继续提问。 😊

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