Java 小数格式化终极指南:4 种方法完美保留两位小数

在Java中格式化小数并保留两位小数,可以通过以下几种方法实现:

1. 使用 DecimalFormat 类

import java.text.DecimalFormat;
import java.math.RoundingMode;

public class DecimalFormatExample {
    public static void main(String[] args) {
        double number = 3.1415;

        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP); // 设置四舍五入模式

        String formatted = df.format(number);
        System.out.println(formatted); // 输出:3.14
    }
}

说明:

模式 “0.00”:强制保留两位小数,不足补零(例如 2.5 格式化为 2.50)。

RoundingMode.HALF_UP:四舍五入规则(3.145 → 3.15)。

2. 使用 String.format()

public class StringFormatExample {
    public static void main(String[] args) {
        double number = 3.1415;

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

说明:

格式字符串 “%.2f”:自动保留两位小数,不足补零。

Locale 问题:默认使用系统区域设置,如需固定小数点符号为.,可指定 Locale.US:

String formatted = String.format(Locale.US, "%.2f", number);

3. 使用 BigDecimal(高精度计算)

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalExample {
    public static void main(String[] args) {
        double number = 3.145;

        BigDecimal bd = BigDecimal.valueOf(number);
        bd = bd.setScale(2, RoundingMode.HALF_UP);

        String formatted = bd.toString();
        System.out.println(formatted); // 输出:3.15
    }
}

说明:

BigDecimal.valueOf(number):避免直接使用 new BigDecimal(double) 导致的精度问题。

setScale(2, RoundingMode.HALF_UP):设置小数位数和舍入模式。

4. 使用 NumberFormat(本地化格式)
java
复制

import java.text.NumberFormat;
import java.util.Locale;

public class NumberFormatExample {
    public static void main(String[] args) {
        double number = 1234.567;

        NumberFormat nf = NumberFormat.getInstance(Locale.US);
        nf.setMinimumFractionDigits(2);
        nf.setMaximumFractionDigits(2);

        String formatted = nf.format(number);
        System.out.println(formatted); // 输出:1,234.57(含千分位分隔符)
    }
}

说明:

setMinimumFractionDigits(2) 和 setMaximumFractionDigits(2):固定两位小数。

Locale.US:指定小数点符号为 .,千分位分隔符为 ,。

总结

方法适用场景特点
DecimalFormat灵活自定义格式(如货币、百分比)需设置模式,支持复杂格式
String.format()快速简单格式化代码简洁,适合基础需求
BigDecimal高精度计算(如金融场景)避免浮点数精度问题
NumberFormat本地化格式(如千分位分隔符)支持国际化,自动处理区域差异

根据需求选择最合适的方法,确保正确处理四舍五入和精度问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ybg8912

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值