round BigDecimal to nearest 5 cents

Using BigDecimal without any doubles (improved on the answer from marcolopes): public static BigDecimal round(BigDecimal value, BigDecimal increment, RoundingMode roundingMode) { if (increment.signum() == 0) { // 0 increment does not make much sense, but prevent division by 0 return value; } else { BigDecimal divided = value.divide(increment, 0, roundingMode); BigDecimal result = divided.multiply(increment); return … Read more

How can I parse a String to BigDecimal? [duplicate]

Try this // Create a DecimalFormat that fits your requirements DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setGroupingSeparator(‘,’); symbols.setDecimalSeparator(‘.’); String pattern = “#,##0.0#”; DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols); decimalFormat.setParseBigDecimal(true); // parse the string BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse(“10,692,467,440,017.120”); System.out.println(bigDecimal); If you are building an application with I18N support you should use DecimalFormatSymbols(Locale) Also keep in mind … Read more

BigDecimal adding wrong value

Use a String literal: private static final BigDecimal sd = new BigDecimal(“0.7”); If you use a double, actually public BigDecimal(double val) is called. The reason you do not get 0.7 is that it cannot be exactly represented by a double. See the linked JavaDoc for more information.

BigDecimal in JavaScript

Since we have native support for BigInt, it doesn’t require much code any more to implement BigDecimal. Here is a BigDecimal class based on BigInt with the following characteristics: The number of decimals is configured as a constant, applicable to all instances. Whether excessive digits are truncated or rounded is configured as a boolean constant. … Read more

Java BigDecimal precision problems

What you actually want is new BigDecimal(“0.1”) .add(new BigDecimal(“0.1”)) .add(new BigDecimal(“0.1”)); The new BigDecimal(double) constructor gets all the imprecision of the double, so by the time you’ve said 0.1, you’ve already introduced the rounding error. Using the String constructor avoids the rounding error associated with going via the double.

Removing trailing zeros from BigDecimal in Java

Use toPlainString() BigDecimal d = new BigDecimal(“600.0”).setScale(2, RoundingMode.HALF_UP).stripTrailingZeros(); System.out.println(d.toPlainString()); // Printed 600 for me I’m not into JSF (yet), but converter might look like this: @FacesConverter(“bigDecimalPlainDisplay”) public class BigDecimalDisplayConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { throw new BigDecimal(value); } @Override public String getAsString(FacesContext context, UIComponent component, Object value) … Read more