Java examples for java.math:BigDecimal Calculation
Add n BigDecimal safely
//package com.java2s; import java.math.BigDecimal; public class Main { public static void main(String[] argv) throws Exception { BigDecimal start = new BigDecimal("1234"); BigDecimal values = new BigDecimal("1234"); System.out.println(add(start, values)); }/*from w w w . j a v a 2 s . c o m*/ /** * Add n BigDecimal safely (i.e. handles nulls) */ public static BigDecimal add(final BigDecimal start, final BigDecimal... values) { BigDecimal total = start != null ? start : BigDecimal.ZERO; if (values != null) { for (final BigDecimal v : values) { total = doAdd(total, v); } } return total; } public static BigDecimal add(final String start, final String... values) { BigDecimal total = start != null ? new BigDecimal(start) : BigDecimal.ZERO; if (values != null) { for (final String v : values) { total = doAdd(total, new BigDecimal(v)); } } return total; } /** * Add 2 BigDecimal safely (i.e. handles nulls) */ private static BigDecimal doAdd(final BigDecimal v1, final BigDecimal v2) { BigDecimal total = v1; if (v1 != null && v2 != null) { total = v1.add(v2); } else if (v2 != null) { total = v2; } return total; } }