随笔 - 43  文章 - 0  评论 - 0  阅读 - 3021

BigDecimal类

思考代码输出结果

public class TestBigDecimal {
    public static void main(String[] args) {
        double d1 = 1.0;
        double d2 = 0.9;
        System.out.println(d1-d2);
		
        double result = (1.4 - 0.5) / 0.9;
        System.out.println(result);
    }
}

image

很多实际应用中需要精确运算,而double是近似值存储,不在符合要求,需要借助BlgDecimal

BigDecimal

  • 位置:java.math包中。
  • 作用:精确计算浮点数。
  • 创建方式:BigDecimal bd = new BigDecimal("1.8");
public class TestBigDecimal {
    public static void main(String[] args) {
        //BigDecimal,大的浮点数的精确计算
        BigDecimal bd = new BigDecimal("1.0");
        BigDecimal bd2 = new BigDecimal("0.9");
        //减法:subtract
        BigDecimal r1 = bd.subtract(bd2);
        System.out.println(r1);
        //加法:add
        BigDecimal r2 = bd.add(bd2);
        System.out.println(r2);
        //乘法:multiply
        BigDecimal r3 = bd.multiply(bd2);
        System.out.println(r3);
        //除法:divide
        BigDecimal r4 = new BigDecimal("1.4")
                .subtract(new BigDecimal("0.9"))
                .divide(new BigDecimal("0.5"));
        System.out.println(r4);
	//除不尽:四舍五入BigDecimal.ROUND_HALF_UP
        BigDecimal r5 = new BigDecimal("10")
                .divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP);
        System.out.println(r5);
    }
}

image

除法: divide(BigDecimal bd,int scal,RoundingMode mode)

  • 参数scal :指定精确到小数点后几位。
  • 参数mode :
    • 指定小数部分的取舍模式,通常采用四舍五入的模式。
    • 取值为BigDecimal.ROUND_HALF_UP。
posted on   小宇不会编程  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示