简体   繁体   English

BigDecimal在小数点后有2个分数?

[英]BigDecimal with 2 fraction after decimal point?

I'd like to have a BigDecimal formatted with 2 decimals after the decimal point. 我希望在小数点后面有一个格式为2位小数的BigDecimal。 Always. 总是。

Based on some boolean checks, I sometimes return a BigDecimal.ZERO; 根据一些布尔检查,我有时会返回一个BigDecimal.ZERO; In this case, the JSF page just displays "0", although I set <f:convertNumber minFractionDigits="2" maxFractionDigits="2"/> . 在这种情况下,JSF页面只显示“0”,尽管我设置<f:convertNumber minFractionDigits="2" maxFractionDigits="2"/>

I do not understand this, but nevertheless how can I enforce 2 digits else? 我不明白这一点,但是我怎么能强制执行2位数呢?

there are 2 ways of doing this 有两种方法可以做到这一点

you can use the built in BigDecimal function 你可以使用内置的BigDecimal函数

myBigDecimal.SetScale(2, RoundingMode.HALF_UP);

This returns a big decmial with 2 digits past the decimal and also rounds up.(there are also other rounding methods) 这会返回一个大小的十进制数,超过小数后的2位数,也会向上舍入。(还有其他舍入方法)

OR 要么

you could use jsf convertNumber Tag 你可以使用jsf convertNumber标签

<f:convertNumber maxFractionDigits="2" minFractionDigits="2" />

Try formatting the number like this: 尝试格式化这样的数字:

    <h:outputText value="#{myBean.bd1}">
        <f:convertNumber pattern="0.00" />
    </h:outputText>

Note: Please also pay attention to the warnings regarding to rounding in the accepted answer. 注意:请注意接受答案中有关四舍五入的警告。

试试吧

<af:convertNumber maxIntegerDigits="3" maxFractionDigits="2"   minFractionDigits="2" pattern="###.##" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM