Java achieves accurate "four rounds"

xiaoxiao2021-03-06  84

Import java.math.bigdecimal; public class arith {private static final int def_div_scale = 10;

private arch () {

}

/ **

* Provide precise addition operations.

* @Param V1 is added

* @Param V2 plus number

* @return two parameters and

* /

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 ();

}

/ **

* Provide precise subtraction operations.

* @Param V1 is reduced

* @PARAM V2 reduction

* @return 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 ();

}

/ **

* Provide precise multiplication.

* @Param V1 is multiplied

* @Param V2 multiplier

* @Return's product

* /

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, accurate to

* After the decimal point, the number will be rounded in the future.

* @PARAM V1 is divided

* @Param V2 divisor

* @Return two parameters

* /

Public Static Double Div (Double V1, Double V2) {

Return Div (V1, V2, DEF_DIV_SCALE);

}

/ **

* Provide (relatively) precise division operations. When an endless case occurs, the scale parameter refers to

* Define accuracy, the number of numbers in the future.

* @PARAM V1 is divided

* @Param V2 divisor

* @Param Scale means that several digits are required to be accurate to the decimal point.

* @Return 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.divide (b2, scale, bigdecimal.round_half_up) .doubleValue ();

/ **

* Provide precise decimal rounds.

* @Param V Needs a number of four rounds

* @Param scale reserves a few times

* @Return's result

* /

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 ();

}

}

转载请注明原文地址:https://www.9cbs.com/read-122074.html

New Post(0)