Adding up BigDecimals using Streams

I have a collection of BigDecimals (in this example, a LinkedList) that I would like to add together. Is it possible to use streams for this? I noticed the Stream class has several methods Stream::mapToInt Stream::mapToDouble Stream::mapToLong Each of which has a convenient sum() method. But, as we know, float and double arithmetic is almost … Read more

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

I have this little crazy method that converts BigDecimal values into nice and readable Strings. private String formatBigDecimal(BigDecimal bd){ DecimalFormat df = new DecimalFormat(); df.setMinimumFractionDigits(3); df.setMaximumFractionDigits(3); df.setMinimumIntegerDigits(1); df.setMaximumIntegerDigits(3); df.setGroupingSize(20); return df.format(bd); } It however, also produces a so called grouping separator “,” that makes all my values come out like this: xxx,xxx I do need … Read more

Rounding BigDecimal to *always* have two decimal places

I’m trying to round BigDecimal values up, to two decimal places. I’m using BigDecimal rounded = value.round(new MathContext(2, RoundingMode.CEILING)); logger.trace(“rounded {} to {}”, value, rounded); but it doesn’t do what I want consistently: rounded 0.819 to 0.82 rounded 1.092 to 1.1 rounded 1.365 to 1.4 // should be 1.37 rounded 2.730 to 2.8 // should … Read more

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

Why does the following code raise the exception shown below? BigDecimal a = new BigDecimal(“1.6”); BigDecimal b = new BigDecimal(“9.2”); a.divide(b) // results in the following exception. Exception: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. 9 s 9 From the Java 11 BigDecimal docs: When a MathContext object is supplied with a precision … Read more