Import java. Math. bigdecimal;
/**
* Because Java's simple types cannot accurately perform floating-point operations, this tool provides
* A real floating point number operation, including addition, subtraction, multiplication, division, and rounding.
*/
Public class Arith {
// Default division operation precision
Private Static final int def_div_scale = 10;
// This class cannot be instantiated
Private Arith (){
}
/**
* Provides precise addition operations.
* @ Param V1 add count
* @ Param V2 addend
* @ Return the sum of the 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 precise subtraction operations.
* @ Param V1 subtrahend
* @ Param V2 subtrahend
* @ 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 precise multiplication.
* @ Param V1 Multiplier
* @ Param V2 Multiplier
* @ Return the 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 ();
}
/**
* Provides (relatively) accurate Division operations, accurate
* 10 digits after the decimal point, and the digits after the decimal point are rounded down.
* @ Param V1 Divisor
* @ Param V2 Divisor
* @ Return parameter vendors
*/
Public static double Div (double V1, double V2 ){
Return Div (V1, V2, def_div_scale );
}
/**
* Provides (relatively) accurate Division operations. In case of division, the scale parameter indicates
* Set the precision. The number is rounded down.
* @ Param V1 Divisor
* @ Param V2 Divisor
* @ Param scale indicates the number of digits after the decimal point.
* @ Return parameter vendors
*/
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.divide (B2, scale, bigdecimal. round_half_up). doublevalue ();
}
/**
* Provides precise rounding of decimal places.
* @ Param V refers to the number rounded up.
* @ Param scale: number of digits after the decimal point
* @ Return returns the result after rounding.
*/
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. Divide (one, scale, bigdecimal. round_half_up). doublevalue ();
}
};