Java floating-point types need to use the JAVA.MATH.* Toolkit, so the results are what we want. Oh
1 ImportJava.math.BigDecimal;2 ImportJava.text.NumberFormat;3 4 5 /**6 * Mathematical Calculation class7 * @authorMingge8 *9 */Ten Public classArithutil { One A PrivateArithutil () { - - } the - /** - * Floating-point addition - * @paramNUM1 + * @paramnum2 - * @return + */ A Public Static DoubleAddDoubleNUM1,Doublenum2) { atBigDecimal v1=bigdecimal.valueof (NUM1); -BigDecimal v2=bigdecimal.valueof (num2); - returnV1.add (v2). Doublevalue (); - } - - /** in * Floating-point subtraction - * @paramNUM1 to * @paramnum2 + * @return - */ the Public Static DoubleSubDoubleNUM1,Doublenum2) { *BigDecimal v1=bigdecimal.valueof (NUM1); $BigDecimal v2=bigdecimal.valueof (num2);Panax Notoginseng returnv1.subtract (v2). Doublevalue (); - } the + /** A * Two number multiplication the * @paramNUM1 + * @paramnum2 - * @return $ */ $ Public Static DoubleMulDoubleNUM1,Doublenum2) { -BigDecimal v1=bigdecimal.valueof (NUM1); -BigDecimal v2=bigdecimal.valueof (num2); the returnv1.multiply (v2). Doublevalue (); - }Wuyi the /** - * Two number of divisions, except for endless rounding Wu * @paramNUM1 - * @paramnum2 About * @param Scale $ * @return - */ - Public Static DoubleDivDoubleNUM1,DoubleNUM2,intScale ) { - if(scale<0) { A Throw NewIllegalArgumentException ("parameter exception ... "); + } theBigDecimal v1=bigdecimal.valueof (NUM1); -BigDecimal v2=bigdecimal.valueof (num2); $ returnv1.divide (v2,scale,bigdecimal.round_half_up). Doublevalue (); the } the the the /** - * Reserved two decimal places in * @return the */ the Public Static DoubleChangetwodecimal (Doubled) { AboutNumberFormat NF =numberformat.getnumberinstance (); theNf.setmaximumfractiondigits (2); the returndouble.valueof (Nf.format (d)); the } + - /** the * Retain the specified number of digitsBayi * @paramD the * @param Scale the * @return - */ - Public Static DoubleChangedecimal (DoubleDintScale ) { theBigDecimal BG =NewBigDecimal (d); the DoubleValue =Bg.setscale (scale, bigdecimal.round_half_up). Doublevalue (); the returnvalue; the - } the the the 94 the the Public Static voidMain (string[] args) { theSystem.out.println (Arithutil.changetwodecimal (5.60));98System.out.println (Arithutil.changedecimal (6.356d, 5)); About } - 101 102 103 104}
This tool class is temporarily written here, still need to continue to optimize ... Knowledge economy is a constant improvement.
Java floating-point type calculation