Adding up BigDecimals using Streams

Original answer Yes, this is possible: List<BigDecimal> bdList = new ArrayList<>(); //populate list BigDecimal result = bdList.stream() .reduce(BigDecimal.ZERO, BigDecimal::add); What it does is: Obtain a List<BigDecimal>. Turn it into a Stream<BigDecimal> Call the reduce method. 3.1. We supply an identity value for addition, namely BigDecimal.ZERO. 3.2. We specify the BinaryOperator<BigDecimal>, which adds two BigDecimal‘s, via … Read more

How to change the decimal separator of DecimalFormat from comma to dot/point?

You can change the separator either by setting a locale or using the DecimalFormatSymbols. If you want the grouping separator to be a point, you can use an european locale: NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN); DecimalFormat df = (DecimalFormat)nf; Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers … Read more

How to check if BigDecimal variable == 0 in java?

Use compareTo(BigDecimal.ZERO) instead of equals(): if (price.compareTo(BigDecimal.ZERO) == 0) // see below Comparing with the BigDecimal constant BigDecimal.ZERO avoids having to construct a new BigDecimal(0) every execution. FYI, BigDecimal also has constants BigDecimal.ONE and BigDecimal.TEN for your convenience. Note! The reason you can’t use BigDecimal#equals() is that it takes scale into consideration: new BigDecimal(“0”).equals(BigDecimal.ZERO) // … Read more

Compare if BigDecimal is greater than zero

It’s as simple as: if (value.compareTo(BigDecimal.ZERO) > 0) The documentation for compareTo actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo method only guarantees less than zero, zero, or greater than zero for the appropriate three cases – so I typically just stick to that comparison.

Double vs. BigDecimal?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen. The disadvantage of BigDecimal is that … Read more

ArithmeticException: “Non-terminating decimal expansion; no exact representable decimal result”

From the Java 11 BigDecimal docs: When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.) As a corollary of computing the exact … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)