first edition
There are several parameters in java.math().RoundingMode that make me a little dizzy. Now I summarize them one by one with my personal understanding:
RoundingMode.CEILING: take the nearest integer on the right
RoundingMode.DOWN: remove the decimal part for rounding, that is, the positive number takes the left and the negative number takes the right, which is equivalent to rounding in the direction close to the origin
RoundingMode.FLOOR: take the nearest positive number on the left
RoundingMode.HALF_DOWN: rounding. Negative numbers take the absolute value first, then rounding and then negative numbers
RoundingMode.HALF_UP: rounding. The principle of negative numbers is the same as above
RoundingMode.HALF_EVEN: this comparison is rounded. If the integer bit is odd, it will be rounded. If it is even, it will be rounded
Second Edition
roundMode refers to the mode when rounding. Bigdecimal.round is used when transmitting parameters_ XXXX_ XXX,
The following example is setScale(0,BigDecimal.ROUND_XXXX_XXX)); The situation. If the reserved decimal places are not zero, such as
setScale(2,BigDecimal.ROUND_XXXX_XXX)); If it is 2, the decimal places of this number should be greater than 2. The third is the choice.
ROUND_CEILING: move 1.1 - > 2 1.5 - > 2 1.8 - > 2 - 1.1 - > - 1 - 1.5 - > - 1 - 1.8 - > - 1 in the positive infinite direction when rounding
ROUND_DOWN: move 1.1 - > 1 1.5 - > 1 1 1.8 - > 1 - 1.1 - > - 1 - 1.5 - > - 1 - 1.8 > - 1 in the direction of 0
ROUND_FLOOR: Contrary to CEILING, go to negative infinity 1.1 - > 1 1.5 - > 1 1 1.8 - > 1 - 1.1 - > - 2 - 1.5 - > - 2 - 1.8 - > - 2
ROUND_HALF_DOWN: take 5 as the dividing line, or rounding 1.5 - > 1.6 - > 1 - 1.5 - > 1 - 1.6 - > 2 1.15 - > 1.1 1.16 - > 1.2 1.55 - > 1.6 1.56 - > 1.6
ROUND_HALF_EVEN: also take 5 as the dividing line. If it is 5, the previous digit becomes even 1.15 - > 1.2, 1.16 - > 1.2, 1.25 - > 1.2, 1.26 - > 1.3
ROUND_HALF_UP: most common rounding
ROUND_UNNECESSARY: no rounding is required
ROUND_UP: and ROUND_DOWN, direction away from 0 1.1 - > 2 1.5 - > 2 1.8 - > 2 - 1.1 - > 2 - 1.5 - > 2 - 1.8 - > 2
Specific accuracy to several digits, so it should be adopted
Quotient = divisor. Devide (divisor, decimal places reserved, exact method)
Third Edition
BigDecimal consists of an integer non scale value of arbitrary precision and a 32-bit integer scale. If zero or positive, the scale is the number of digits after the decimal point. If it is negative, the non scale value of the number is multiplied by the negative scale power of 10. Therefore, the value represented by BigDecimal is (unscaledValue) × 10-scale).
It can handle floating-point operations of any length.
BigDecimal subtract (BigDecimal val) //BigDecimal subtraction
BigDecimal divide (BigDecimal Val, roundingmode) Division
Specific usage calculation:
Minus: a.subtract(b);
Except: A. divide (B, 2)// 2 is the detailed solution of precision value division: / / note that the following division will throw an exception. Reason: when dividing through BigDecimal's divide method, if there is no integral division and infinite circular decimal, the exception will be thrown / / BigDecimal divideBg = a.divide(b)// The solution is: set the accuracy; Set the exact decimal point of divide(xxxxx,2, BigDecimal.ROUND_HALF_EVEN) / / the second parameter indicates the number of digits after the decimal point
Let's take a look at the detailed description of division: divide (BigDecimal division, int scale, ingroundingmode)
setScale method of BigDecimal
BigDecimal.setScale()
Method to format the decimal point
It means to keep one decimal place, which is rounded by default
setScale(1)
Delete the extra decimal places directly. For example, 2.35 will become 2.3 setScale(1,BigDecimal.ROUND_DOWN)
Carry processing, 2.35 becomes 2.4 setScale(1,BigDecimal.ROUND_UP)
Rounding, 2.35 becomes 2.4 setScale(1,BigDecimal.ROUND_HALF_UP)
Round off, 2.35 becomes 2.3. If it is 5, round down setScaler(1,BigDecimal.ROUND_HALF_DOWN)
Be careful
scale refers to the number of digits after your decimal point.
scale() is the method in the BigDecimal class. as
BigDecimal b = new BigDecimal("123.456");
b.scale() returns 3
Attention point two
roundingMode is the decimal retention mode. They are constant fields in BigDecimal,
There are many kinds, such as
BigDecimal.ROUND_HALF_UP means 4 to 5
Pay attention to point three
BigDecimal bb=new BigDecimal("100" );
BigDecimal type in java can be converted to double type: use variable. doubleValue(); Function can convert BigDecimal type data to double type! 4.java BigDecimal size comparison
Take the following example: BigDecimal a = new BigDecimal("1.00"); BigDecmial b = new BigDecimal(1);
System.out.println(a.equals(b)); But the output result is: false. The reason is: when BigDecimal is compared, it not only compares the value, but also compares the accuracy?
if(a.compareTo(b)==0) the result is true
BigDecimal takes the maximum, minimum, absolute and opposite values:
a.min(b) / / take the minimum value for comparison
a.negate() / / take the opposite number
Here are the notes:
BigDecimal enumeration constant Usage Summary:
CEILING
A rounding pattern that rounds to positive infinity.
DOWN
Rounding mode for rounding to zero.
FLOOR
A rounding pattern rounded to negative infinity.
HALF_DOWN
A rounding pattern that rounds in the direction closest to the number. If the distance from two adjacent numbers is equal, it is rounded down.
HALF_EVEN
The rounding mode of rounding in the direction closest to the number. If the distance from two adjacent numbers is equal, it is rounded to the adjacent even number.
HALF_UP
A rounding pattern that rounds in the direction closest to the number. If the distance from two adjacent numbers is equal, it is rounded up.
UNNECESSARY
The operation used to assert the request has a rounding pattern of exact results, so rounding is not required.
UP
Rounding mode for rounding away from zero.
About BigDecimal formatting
public String formatValue(Object value){ String content = null; if (value == null) { content = ""; } else { if(value instanceof BigDecimal){ //conver to fortmat String NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(2); nf.setMaximumFractionDigits(2); content = nf.format(value); }else{ content = String.valueOf(value); } } return content; }
The formatting effect can be achieved by using such a method. value instanceof BigDecimal indicates that the character type is executed when the character type is BigDecimal. Here, NumberFormat represents the character type, and the following two sentences of code represent the exact number of digits after the decimal point.
There are also two other types of NumberFormat:
getCurrencyInstance(): returns the currency format of the current default environment
CurrencyInstance(): returns the number format of the specified locale, generally in percentage format
This principle is also mentioned in Effective Java. float and double can only be used for scientific calculation or engineering calculation. In business calculation, we should use java.math.BigDecimal.
If we need accurate calculation, we have to use String to build BigDecimal!
The following tool class is a reprint of others. You can accurately calculate the decimal through a tool class.
import java.math.BigDecimal; /** *//** * Because Java's simple types can't accurately operate on floating-point numbers, this tool class provides precision * Exact floating-point operations, including addition, subtraction, multiplication, division, and rounding. */ public class Arith{ //Default division precision private static final int DEF_DIV_SCALE = 10; //This class cannot be instantiated private Arith(){ } /** *//** * Provides accurate addition operations. * @param v1 augend * @param v2 Addend * @return Sum of two parameters */ public static double add(double v1,double v2){ BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2).doubleValue(); } /** *//** * Provides accurate subtraction. * @param v1 minuend * @param v2 Subtraction * @return Difference between two parameters */ public static double sub(double v1,double v2){ BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2).doubleValue(); } /** *//** * Provides accurate multiplication. * @param v1 Multiplicand * @param v2 multiplier * @return Product of two parameters */ public static double mul(double v1,double v2){ BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2).doubleValue(); } /** *//** * Provide (relatively) accurate division operation, which is accurate to when there is inexhaustible division * 10 digits after the decimal point, and the subsequent figures are rounded. * @param v1 Divisor * @param v2 Divisor * @return Quotient of two parameters */ public static double div(double v1,double v2){ return div(v1,v2,DEF_DIV_SCALE); } /** *//** * Provides (relatively) accurate division. In case of inexhaustible division, it is specified by the scale parameter * To determine the accuracy, the subsequent figures are rounded. * @param v1 Divisor * @param v2 Divisor * @param scale Indicates that it needs to be accurate to several decimal places. * @return Quotient of two parameters */ public static double div(double v1,double v2,int scale){ if(scale<0){ throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divid(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue(); } /** *//** * Provide accurate decimal rounding processing. * @param v Number to be rounded * @param scale How many decimal places are reserved * @return Rounded results */ public static double round(double v,int scale){ if(scale<0){ throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divid(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue(); } }
BigDecimal consists of an integer non scale value of arbitrary precision and a 32-bit integer scale. If zero or positive, the scale is the number of digits after the decimal point. If it is negative, the non scale value of the number is multiplied by the negative scale power of 10. Therefore, the value represented by BigDecimal is (unscaledValue) × 10-scale).
It can handle floating-point operations of any length.
BigDecimal add(BigDecimal val) //BigDecimal add
BigDecimal subtract (BigDecimal val) //BigDecimal subtraction
BigDecimal multiply (BigDecimal val) //BigDecimal multiply
BigDecimal divide (BigDecimal Val, roundingmode) Division
Specific usage calculation:
Add: a.add(b);
Minus: a.subtract(b);
Multiply: a.multiply(b);
Except: A. divide (B, 2)// 2 is the precision value
Division solution:
//Note that the following division will throw an exception. Reason: when dividing through BigDecimal's divide method, an exception will be thrown when there is no integral division and an infinite circular decimal
//BigDecimal divideBg = a.divide(b);
//The solution is: set the accuracy; Is to set the exact decimal point for divide
divide(xxxxx,2, BigDecimal.ROUND_HALF_EVEN)
//The second parameter indicates the number of digits after the decimal point
BigDecimal does not divide the thrown exception, please set the accuracy!
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.math.BigDecimal.divide(BigDecimal.java:1278) at main.Main.main(Main.java:41)