Java –如何将double / float值四舍五入到2个小数点

在Java中,有几种方法可以将floatdouble舍入到小数点后double

注意
阅读此RoundingMode

1. DecimalFormat

DecimalExample.java
package com.mkyong;

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

public class DecimalExample {

    private static DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) {

        double input = 1205.6358;

        System.out.println("salary : " + input);

        // DecimalFormat, default is RoundingMode.HALF_EVEN
        System.out.println("salary : " + df.format(input));      //1205.64
        
        df.setRoundingMode(RoundingMode.DOWN);
        System.out.println("salary : " + df.format(input));      //1205.63

        df.setRoundingMode(RoundingMode.UP);
        System.out.println("salary : " + df.format(input));      //1205.64

    }

}

输出量

salary : 1205.6358
salary : 1205.64
salary : 1205.63
salary : 1205.64

2. BigDecimal

BigDecimalExample.java
package com.mkyong;

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

public class BigDecimalExample {

    public static void main(String[] args) {

        double input = 3.14159265359;
        System.out.println("double : " + input);

        BigDecimal bd = new BigDecimal(input).setScale(2, RoundingMode.HALF_UP);
        double salary = bd.doubleValue();

        System.out.println("salary : " + salary);

    }

}

输出量

salary : 1205.6358
salary : 1205.64

3. Math.round

MathExample.java
package com.mkyong;

public class MathExample {

    public static void main(String[] args) {

        double input = 1205.6358;

        System.out.println("salary : " + input);

        double salary = Math.round(input * 100.0) / 100.0;

        System.out.println("salary : " + salary);

    }

}

输出量

salary : 1205.6358
salary : 1205.64

说明,仅用于学术目的,保留三位小数, *1000

input = 1205.6358;

Math.round(input * 100.0) / 100.0;

Math.round(120563.58) / 100.0;

120564 / 100.0;

salary = 1205.64

参考文献

翻译自: https://mkyong.com/java/how-to-round-double-float-value-to-2-decimal-points-in-java/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值