Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

Removing trailing zeros from BigDecimal in Java

I need to remove trailing zeros from BigDecimal along with RoundingMode.HALF_UP. 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.

stripTrailingZeros() works but it returns scientific notations in situations like,

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

In this case, it returns 6E+2. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {
        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" />
</h:inputText>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...