* In Java, the default declaration of decimals is a double type;
* Double d=4.0
* If stated:
float x=4.0;
* Float x = 4.0 will be an error, you need to use the following wording:
float x = 4.0f; where the F after 4.0f is just to distinguish double, does not mean any number on the meaning of float x1 = (float) 4.0;
Folat differs from Double:
* Float memory allocation 4 bytes, accounting for 32 bits, effective decimal bit 6-7 bit
* Double type memory allocation 8 bytes, effective decimal bit 15 bit
* This principle is also mentioned in the book "Effective Java": float and double can only be used for scientific calculations or engineering calculations; We need to use java.math.BigDecimal in business calculations.
Use the Java.math.BigDecimal class for calculations:
/*** provides accurate mathematical operations. * @paramv1 (addend, meiosis, Divisor,,) *@paramv2 addend, meiosis 、、、 *@returntwo parameters (and, except, product, difference)*/ //addition Public Static DoubleAddDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); returnB1.add (B2). Doublevalue (); } //Subtraction Public Static DoubleSubDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); returnb1.subtract (B2). Doublevalue (); } //multiplication Public Static DoubleMulDoubleV1,Doublev2) {BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); returnb1.multiply (B2). Doublevalue (); } /*provides (relative) precise division operations. When the exception occurs, the scale parameter refers to the fixed precision, and the subsequent numbers are rounded. * @param scale indicates the need to be accurate to several decimal places. */ Public Static DoubleDivDoubleV1,DoubleV2,intScale ) { if(scale<0){ Throw NewIllegalArgumentException ("The scale must is a positive integer or zero"); } BigDecimal B1=NewBigDecimal (double.tostring (v1)); BigDecimal B2=NewBigDecimal (Double.tostring (v2)); returnb1.divide (b2,scale,bigdecimal.round_half_up). Doublevalue (); }
Provides precise rounding of decimal digits:
/*** Provides precise rounding of decimal digits. * @paramv need to round the number *@paramA few * after the decimal point@returnresults after rounding*/ Public Static DoubleRoundDoubleVintScale ) { if(scale<0){ Throw NewIllegalArgumentException ("The scale must is a positive integer or zero"); } BigDecimal b=NewBigDecimal (double.tostring (v)); BigDecimal One=NewBigDecimal ("1"); returnb.divide (one,scale,bigdecimal.round_half_up). Doublevalue (); }
float and double