当前位置:网站首页>BigDecimal. Summary of setscale usage

BigDecimal. Summary of setscale usage

2022-06-25 06:19:00 WD Technology

  1. ROUND_DOWN( Directly omit the contents after the specified number of digits )
    BigDecimal bigDecimal = new BigDecimal(“2.125456”).setScale(2, BigDecimal.ROUND_DOWN);

System.out.println(bigDecimal ); // result :2.12

  1. ROUND_UP( Directly perform one bit processing on the content after the specified number of bits )
    BigDecimal bigDecimal = new BigDecimal(“2.125456”).setScale(2, BigDecimal.ROUND_UP);

System.out.println(bigDecimal); // result :2.13

  1. ROUND_CEILING( Positive numbers use ROUND_UP The rules , Negative numbers use ROUND_DOWN The rules )
    BigDecimal bigDecimalA = new BigDecimal(“2.125456”).setScale(2, BigDecimal.ROUND_CEILING);

System.out.println(bigDecimalA);// result :2.13

BigDecimal bigDecimalB = new BigDecimal("-2.125456").setScale(2, BigDecimal.ROUND_CEILING);

System.out.println(bigDecimalB);// result :2.12

  1. ROUND_FLOOR( Positive numbers omit content , Negative numbers go down one digit )
    BigDecimal bigDecimalA = new BigDecimal(“2.125456”).setScale(2, BigDecimal.ROUND_FLOOR);

System.out.println(bigDecimalA);// result :2.12

BigDecimal bigDecimalB = new BigDecimal("-2.125456").setScale(2, BigDecimal.ROUND_FLOOR);

System.out.println(bigDecimalB);// result :-2.13

  1. ROUND_HALF_UP,ROUND_HALF_DOWN( rounding )
    BigDecimal bigDecimalA = new BigDecimal(“2.125456”).setScale(2, BigDecimal.ROUND_HALF_UP);

System.out.println(bigDecimalA);// result :2.13

BigDecimal bigDecimalB = new BigDecimal("-2.125456").setScale(2, BigDecimal.ROUND_HALF_DOWN);

System.out.println(bigDecimalB);// result :-2.13

  1. ROUND_HALF_EVEN( If the first digit of the specified decimal place is an odd number, it will be rounded to the last digit , If it is an even number, the contents after the specified decimal places will be discarded )
    BigDecimal bigDecimalA = new BigDecimal(“2.113”).setScale(2, BigDecimal.ROUND_HALF_EVEN);

System.out.println(bigDecimalA);// result :2.11 Although it is an odd number , however 3<5, No carry

BigDecimal bigDecimalB = new BigDecimal(“2.115”).setScale(2, BigDecimal.ROUND_HALF_EVEN);

System.out.println(bigDecimalB);// result :2.12 Because it is an odd number and conforms to " Five in ", Then carry

This rounding mode is also known as “ Banker's Rounding ”, Mainly used in the United States . Round to the nearest , In two fifths .

If the previous one is odd , Then enter , Otherwise, give up .

8.ROUND_UNNECESSARY( Assert that the requested operation has exact results , So no rounding is required .)
If this rounding mode is specified for the operation to get accurate results , Throw out ArithmeticException

原网站

版权声明
本文为[WD Technology]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202201237011219.html

随机推荐