1

Getting error: java.lang.NullPointerException: Cannot read field "scale" because "multiplicand" is null. How to avoid this error?

BigDecimal price =  tariffs.stream() //
        .map(tariff -> tariff.getPrice()) //
        .reduce(BigDecimal.ZERO, BigDecimal::add);

BigDecimal productPrice = price.multiply(q).setScale(2, RoundingMode.HALF_UP);
TtT
  • 63
  • 4

1 Answers1

1

q is null. Simple as that. Make q be not null and this error goes away. See this SO question for more information. For example, by initializing it to BigDecimal.ONE, perhaps.

NB: Note that it's generally a lot easier and just all around better to use ints and longs for currency and not BigDecimal. Store the atomary unit of the currency in there: $12.34 becomes 1234. Every currency has this concept, even bitcoin (satoshis). You can't ask a bank to transfer half a cent, so the fact that you can store half a cent in a BigDecimal isn't actually all that useful. BigDecimal isn't a 'but it can handle all cases' thing either; after all, given 4 cents, you can't distribute that evenly amongst 3 people without errors, either. Even with BigDecimal.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72