Skip to content

Instantly share code, notes, and snippets.

@ederrafo
Last active December 25, 2023 22:29
Show Gist options
  • Save ederrafo/7998d68c717e8d2452fd512375034aa8 to your computer and use it in GitHub Desktop.
Save ederrafo/7998d68c717e8d2452fd512375034aa8 to your computer and use it in GitHub Desktop.
java bigdecimal
0 : if value of this BigDecimal is equal to that of BigDecimal object passed as parameter.
1 : if value of this BigDecimal is greater than that of BigDecimal object passed as parameter.
-1 : if value of this BigDecimal is less than that of BigDecimal object passed as parameter.
  if (accountingInvoice.getRetention().getAmount().compareTo(BigDecimal.ZERO) == 1) {
   hasRetention = true;
  }

Sum all bigdecimal in list

BigDecimal sum = foundCostCenters
          .stream()
          .map( p -> p.getPercentage())
          .reduce(BigDecimal.ZERO, BigDecimal::add);

Format BigDecimal numbers with comma and 2 decimal place

Want:

Amount is: 5.0001 and formatted to: 5.00
Amount is: 999999999.999999 and formatted to: 999,999,999.99
Amount is: 1000.4999 and formatted to: 1,000.49
Amount is: 9999.089 and formatted to: 9,999.08
Amount is: 0.19999 and formatted to: 0.19
Amount is: 123456.99999999 and formatted to: 123,456.99

solution:

 DecimalFormat decimalFormat = new DecimalFormat("#,##0.000");
 decimalFormat.format(BigDecimal(123456,78)); //will output 123.456,78 - depending on Locale

scale two decimals

con setScale y con RoundingMode.HALF_UP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment