在Java中从BigDecimal中删除尾随零 [英] Removing trailing zeros from BigDecimal in Java
本文介绍了在Java中从BigDecimal中删除尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从 BigDecimal
以及 RoundingMode.HALF_UP
中删除尾随零。例如,
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()
有效,但在类似情况下会返回科学记数法
stripTrailingZeros()
works but it returns scientific notations in situations like,
new BigDecimal("600.0").setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
在这种情况下,它返回 6E + 2
。我需要在JSF中的自定义转换器中使用它,这对最终用户来说可能很难看。那么,这样做的正确方法是什么?
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?
推荐答案
BigDecimal d = new BigDecimal("600.0").setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
System.out.println(d.toPlainString()); // Printed 600 for me
我还没有进入JSF(但是)转换器可能看起来像这个:
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();
}
}
然后在xhtml中:
<h:inputText id="bigDecimalView" value="#{bigDecimalObject}"
size="20" required="true" label="Value">
<f:converter converterId="bigDecimalPlainDisplay" />
</h:inputText>
这篇关于在Java中从BigDecimal中删除尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文