小技巧之4种方式保留小数点后2位四舍五入

最近一段时间属实不知道应该学点啥,写点啥,许多的技术都是知道(略懂)而已,但是懒得花时间投入去深挖,依据个人的性格一项技术挖透得耗费非常非常多的时间,虽然有足够的耐心,但目前真的是有些动力不足,学点啥都不想学,但是又常感叹于不能不去学点啥,所以在不知道学点啥之际翻到了我的浏览器收藏夹,翻了许多后翻到了用Java怎么做“https://howtodoinjava.com/”这个网址,记不得啥时候收藏了,看了一部分Java基础的内容,有一些文章看起来还是值得积累收藏的,所以在参考这些文章的同时,也站在些个人理解的层度,围绕相关技术知识点来普及一下个人的了解。

回到正题,本文将以4种方式来实现格式化保留小数点后2位,并且四舍五入的实现,主要是BigDecimal、Commons Math3、JDK Math、DecimalFormat的几种实现方式,参考代码如下:

package cn.chendd.tips.examples.howtodoinjava.roundoff;

import org.apache.commons.math3.util.Precision;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

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

/**
 * 四舍五入 验证
 *
 * @author chendd
 * @date 2023/4/16 18:10
 */
@RunWith(JUnit4.class)
public class RoundOffTest {

    private final Double value = 12345.56789;

    @Test
    public void bigDecimal() {
        BigDecimal result = new BigDecimal(this.value).setScale(2 , RoundingMode.HALF_UP);
        Assert.assertEquals(result.toString() , "12345.57");
    }

    @Test
    public void commonsMath() {
        double result = Precision.round(this.value, 2, RoundingMode.HALF_UP.ordinal());
        Assert.assertEquals(Double.toString(result), "12345.57");
    }

    @Test
    public void jdkMath() {
        double scale = Math.pow(10, 2);
        double result = Math.round(this.value * scale) / scale;
        Assert.assertEquals(Double.toString(result), "12345.57");
    }

    @Test
    public void decimalFormat() {
        DecimalFormat format = new DecimalFormat("###.##");
        String result = format.format(this.value);
        Assert.assertEquals(result, "12345.57");
    }

}

几种方式都比较简单,至于什么场景下去使用格式化多少位等可自行衡量,源码项目工程可见:“https://gitee.com/88911006/chendd-examples/tree/master/tips”。

参见文个人博客:保留小数点后2位四舍五入

保留小数点后2位四舍五入欢迎来到陈冬冬的个人经验分享平台https://www.chendd.cn/blog/article/1647537173468864513.html

猜你喜欢

转载自blog.csdn.net/haiyangyiba/article/details/130187071