Do a 1570 math, and the result is 0.
Is it a little surprising?
How do we fix that?
Turn into a double type, and then there's no problem.
Import Java.math.BigDecimal; public class Arith {private static final int def_div_scale = 10; /** * * Two double numbers added * * * @param v1 * * @param v2 * * @return double */public static double Add (double v1, double v2) { BigDecimal B1 = new BigDecimal (v1.tostring ()); BigDecimal b2 = new BigDecimal (v2.tostring ()); return new Double (B1.add (B2). Doublevalue ()); /** * * Two double number subtraction * * * @param v1 * * @param v2 * * @return Double */public static double sub (double v1, double V2) {BigDecimal B1 = new BigDecimal (v1.tostring ()); BigDecimal b2 = new BigDecimal (v2.tostring ()); return new Double (B1.subtract (B2). Doublevalue ()); }/** * * Two double multiply * * * @param v1 * * @param v2 * * @return double */public static double Mul (double v1, double V2) {BigDecimal B1 = new BigDecimal (v1.tostring ()); BigDecimal b2 = new BigDecimal (v2.tostring ()); return new Double (B1.multiply (B2). Doublevalue ()); }/** * * Two double number division * * * @param v1 * * @paramV2 * * @return double */public static double div (double v1, double v2) {BigDecimal B1 = new BigDecimal (v1.tostring ( )); BigDecimal b2 = new BigDecimal (v2.tostring ()); return new Double (B1.divide (B2, Def_div_scale, bigdecimal.round_half_up). Doublevalue ()); }/** * * Two double divide, and reserve scale decimal number * * * @param v1 * * @param v2 * * @param scale * * @return Double */public static Double Div (Double v1, double v2, int scale) {if (Scale < 0) {throw new IllegalArgumentException ("the Scale must is a positive integer or zero "); } BigDecimal B1 = new BigDecimal (v1.tostring ()); BigDecimal b2 = new BigDecimal (v2.tostring ()); return new Double (B1.divide (B2, scale, bigdecimal.round_half_up). Doublevalue ()); } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Digital subtraction in Java (especially double type)