Tiny Tiny - 1 year ago 225
Java Question

Removing trailing zeros from BigDecimal in Java

I need to remove trailing zeros from

along with
. For instance,

Value Output

15.3456 <=> 15.35
15.999 <=> 16 //No trailing zeros.
15.99 <=> 15.99
15.0051 <=> 15.01
15.0001 <=> 15 //No trailing zeros.
15.000000<=> 15 //No trailing zeros.
15.00 <=> 15 //No trailing zeros.

works but it returns scientific notations in situations like,

new BigDecimal("600.0").setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();

In this case, it returns
. I need this in a custom converter in JSF where it might be ugly for end users. So, what is the proper way of doing this?

Answer Source

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:

public class BigDecimalDisplayConverter implements Converter {
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        throw new BigDecimal(value);

    public String getAsString(FacesContext context, UIComponent component, Object value) {
        BigDecimal  bd = (BigDecimal)value;
        return bd.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();

and then in xhtml:

<h:inputText id="bigDecimalView" value="#{bigDecimalObject}" 
    size="20" required="true" label="Value">
    <f:converter converterId="bigDecimalPlainDisplay" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download