杰瑞科技汇

Java double如何精确保留小数?

在 Java 中,处理 double 类型保留小数位有多种方法,以下是几种常见的方式及其适用场景:

Java double如何精确保留小数?-图1
(图片来源网络,侵删)

使用 String.format()printf()

适用于需要将数值格式化为字符串的场景,不改变原始数值。

double num = 3.1415926;
String formatted = String.format("%.2f", num); // 保留2位小数,结果为 "3.14"
System.out.println(formatted);
// 使用 printf 直接输出
System.out.printf("%.3f%n", num); // 保留3位小数,输出 "3.142"
  • %.nfn 表示保留的小数位数。
  • %n:平台无关的换行符。

使用 DecimalFormat

适合需要自定义格式(如千位分隔符、科学计数法等)的场景。

import java.text.DecimalFormat;
double num = 12345.6789;
DecimalFormat df = new DecimalFormat("#.##"); // 保留2位小数
String formatted = df.format(num); // 结果为 "12345.68"
System.out.println(formatted);
// 更复杂的格式(如千位分隔符)
DecimalFormat df2 = new DecimalFormat("#,###.00");
System.out.println(df2.format(12345.6789)); // 输出 "12,345.68"
  • :可选数字位(不补零)。
  • 0:强制补零(如 00 会补足两位小数)。

使用 Math.round() 四舍五入

适用于需要四舍五入后返回 doublelong 的场景。

double num = 3.14159;
double rounded = Math.round(num * 100) / 100.0; // 保留2位小数
System.out.println(rounded); // 输出 3.14
// 保留3位小数
double rounded3 = Math.round(num * 1000) / 1000.0;
System.out.println(rounded3); // 输出 3.142
  • 注意:直接使用 Math.round() 会四舍五入到整数,需通过乘除法实现小数位控制。

使用 BigDecimal(精确计算)

强烈推荐用于金融或高精度计算,避免 double 的浮点精度问题。

Java double如何精确保留小数?-图2
(图片来源网络,侵删)
import java.math.BigDecimal;
import java.math.RoundingMode;
double num = 3.1415926;
BigDecimal bd = new BigDecimal(num);
BigDecimal rounded = bd.setScale(2, RoundingMode.HALF_UP); // 保留2位,四舍五入
System.out.println(rounded); // 输出 3.14
// 直接操作字符串更精确
BigDecimal bd2 = new BigDecimal("3.1415926");
System.out.println(bd2.setScale(3, RoundingMode.DOWN)); // 保留3位,直接截断
  • setScale(n, mode):设置小数位数和舍入模式(如 HALF_UP 是四舍五入)。
  • 避免直接用 double 构造 BigDecimal,可能引入精度误差,推荐用字符串构造。

使用 printf 输出时直接控制

适用于直接打印到控制台,不存储格式化结果。

double num = 3.14159;
System.out.printf("保留1位小数: %.1f%n", num); // 输出 "保留1位小数: 3.1"
System.out.printf("保留4位小数: %.4f%n", num); // 输出 "保留4位小数: 3.1416"

如何选择?

方法 适用场景 是否改变原始值 精度问题
String.format() 字符串格式化
DecimalFormat 复杂格式(如千位分隔)
Math.round() 简单四舍五入 可能受 double 精度影响
BigDecimal 高精度计算(金融等) 精确(推荐)
printf 直接输出

推荐

  • 需要精确计算(如金额)→ BigDecimal
  • 需要字符串显示 → String.format()DecimalFormat
  • 简单四舍五入 → Math.round()

示例代码

public class DoubleRounding {
    public static void main(String[] args) {
        double num = 3.1415926;
        // 1. String.format
        System.out.println("String.format: " + String.format("%.2f", num));
        // 2. DecimalFormat
        DecimalFormat df = new DecimalFormat("#.###");
        System.out.println("DecimalFormat: " + df.format(num));
        // 3. Math.round
        double rounded = Math.round(num * 100) / 100.0;
        System.out.println("Math.round: " + rounded);
        // 4. BigDecimal(推荐)
        BigDecimal bd = new BigDecimal(num).setScale(3, RoundingMode.HALF_UP);
        System.out.println("BigDecimal: " + bd);
    }
}

输出结果:

String.format: 3.14
DecimalFormat: 3.142
Math.round: 3.14
BigDecimal: 3.142
Java double如何精确保留小数?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇