Java examples for java.math:BigDecimal Calculation
absolute value Different BigDecimal
//package com.java2s; import java.math.BigDecimal; public class Main { public static void main(String[] argv) throws Exception { BigDecimal v1 = new BigDecimal("1234"); BigDecimal v2 = new BigDecimal("1234"); System.out.println(absDiff(v1, v2)); }/*from ww w .jav a 2 s .c o m*/ /** * @return true if the ABS( ABS(v1) - ABS(v2) ) */ public static BigDecimal absDiff(final BigDecimal v1, final BigDecimal v2) { return abs(doSubtract(abs(v1), abs(v2))); } /** * Returns the ABS of the value, handles null. */ public static BigDecimal abs(final BigDecimal value) { return value != null ? value.abs() : null; } /** * Subtract 2 BigDecimal safely (i.e. handles nulls) v1 - v2 */ private static BigDecimal doSubtract(final BigDecimal v1, final BigDecimal v2) { BigDecimal diff = v1; if (v1 != null && v2 != null) { diff = v1.subtract(v2); } else if (v2 != null) { diff = v2.negate(); } return diff; } /** * Subtract n BigDecimal safely (i.e. handles nulls), returns 0 */ public static BigDecimal subtract(final BigDecimal start, final BigDecimal... values) { BigDecimal total = start != null ? start : BigDecimal.ZERO; if (values != null) { for (final BigDecimal v : values) { total = doSubtract(total, v); } } return total; } /** * Returns the negate of the value, handles null. */ public static BigDecimal negate(final BigDecimal value) { return value != null ? value.negate() : null; } }