当前位置:网站首页>[daily record] - bug encountered in BigDecimal division operation

[daily record] - bug encountered in BigDecimal division operation

2022-07-01 00:54:00 A brief memory of fleeting years

hello ! Hello everyone , Today, I'd like to share with you an article about BigDecimal It occurs once during the division operation bug, I hope it will be helpful and rewarding to you .

Personal blog :https://blog.csdn.net/weixin_43759352

official account :【SimpleMemory】

️️️ If there is a pair of 【 back-end technology 】 Interested bosses , Welcome to your attention !!!️️️

  Recently in the project test environment , Meet such a problem ; Check the log , The error information is as follows :

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1693)

Find... By positioning : Is used in code BigDecimal Of divide Method . 

The inspection found that : This is because in the BigDecimal There is no error to divide the report , So we need to go to divide The function passes in parameter settings to keep several decimal places .

Problem reduction

Here is a test code to demonstrate the scenario without division .

BigDecimal a = new BigDecimal(1);
BigDecimal b = new BigDecimal(3);
BigDecimal result = a.divide(b);
System.out.println("result = " + result);

 

Treatment method

We treat it divide Method , Set the number of decimal places passed in by the parameter , And the specific rounding mode .

BigDecimal result = a.divide(b,2,BigDecimal.ROUND_HALF_UP); //  Keep two decimal places 、 rounding 

If this article 【 article 】 It will help you , I hope you will be more careful Fabulous 、 Comment on 、 Focus on 、 Collection ; If the 【 back-end technology 】 Interested little cute , You are welcome to pay attention to ️️️ official account 【SimpleMemory】️️️, Will continue to bring you 【 Harvest and surprise 】! 

原网站

版权声明
本文为[A brief memory of fleeting years]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202206302329222046.html