1024programmer Blog Addition, subtraction, multiplication and division algorithms commonly used in BigDecimal, size comparison, and saving two decimal points_bigdecimal addition, subtraction, multiplication, and division operations keep two decimal places_wei_wenlong’s blog

Addition, subtraction, multiplication and division algorithms commonly used in BigDecimal, size comparison, and saving two decimal points_bigdecimal addition, subtraction, multiplication, and division operations keep two decimal places_wei_wenlong’s blog

Not much to say, let’s record it first.

BigDecimal coins = new BigDecimal(“0”);

BigDecimal one = new BigDecimal(“1”);

BigDecimal two = new BigDecimal(“2”);

coins = coins.add( two ); //coins plus 2
System.out.println( coins.doubleValue()); //output is 2.0

coins = coins.subtract( one ); //coins minus 1
System.out.println( coins.doubleValue()); //The output is 1.0

coins = coins.multiply( two ); //coins are multiplied by 2
System.out.println( coins.doubleValue()); //The output is 2.0

int i = coins .compareTo(BigDecimal.ZERO) ; //Judge whether coins is greater than 0
int k = coins .compareTo( one ) ;//If i = 0, it means they are equal; if i 0 means coins > one
coins = coins.setScale(2,BigDecimal.ROUND_HALF_UP) //Save two decimal places

Division is trickier:

When the bigdecimal type does division, there is no problem when the result is an integer or a finite decimal. If the result cannot be divisible, an error will be reported for an infinite decimal

Error code:

Bigdecimal bd = num1.divide(c).setScale(6,ROUND_HALF_UP);

Error message: Non-terminating decimal expansion; no exact representable decimal result”

Error translation: infinite decimal expansion; no exact decimal result.

Reason for error: temporarily unknown

Code improvements:

BigDecimal bd = num.divide(c,6,ROUND_HALF_UP);

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索