2014-06-24 36 views
3

例如,在JSF託管bean下面給出。JSF頁面上的BigDecimal算術

@ManagedBean 
@ViewScoped 
public final class Bean implements Serializable { 

    private BigDecimal price; //Getter only. 
    private BigDecimal currencyRate; //Getter only. 
    private static final long serialVersionUID = 1L; 

    @PostConstruct 
    private void init() { 
     price=new BigDecimal(5678); 
     currencyRate=new BigDecimal(0.016622); 
    } 
} 

的乘法pricecurrencyRate可以<h:outputText>顯示。

<h:outputText value="#{bean.price * bean.currencyRate}"/> 

這是否乘法產量BigDecimal或者它只是一個double價值?


換句話說,這相當於以下幾點嗎?

<h:outputText value="#{bean.price.multiply(bean.currencyRate)}"/> 

在兩種情況下都顯示94.3797160000000077070825277303356415359303355216979980468750


如果當有一個顯示指定數量的小數位數,二舉例如下轉換器是什麼?

<h:outputText value="#{bean.price * bean.currencyRate}" 
       converter="#{bigDecimalConverter}"/> 

無論如何,我希望這樣的表達式的結果是BigDecimal

+0

BigDecimal肯定,但它很容易測試自己。 – EJP

+0

我不知道如何測試JSF頁面上的類型。結果在兩種情況下都是一樣的 - '94.3797160000000077070825277303356415359303355216979980468750'。 – Tiny

+0

你*有*只是測試*和*驗證它。如果它是兩倍,你不會得到所有的精度。 – EJP

回答

6

El 3.0 spec pdf(第13頁 - 第1.7.1節):

算術運算符的評價在以下各節中描述。 A和B 是子表達式的評估。

1.7.1二元運算 - A {+, - ,*}乙

  • 如果A和B是null,返回(Long)0
  • 如果A或B是BigDecimal,脅迫既BigDecimal然後:
    • 如果運營商+,返回A.add(B)
    • 如果運營商是 - ,返回0 。
    • 如果操作者是*,返回A.multiply(B)
  • 如果A或B是FloatDouble,或String含有,e或E:
    • 如果A或B是BigInteger,強迫A和B均爲BigDecimal並應用 運營商。
    • 否則,強迫A和B兩者,以Double和應用操作者
  • 如果A或B是BigInteger,脅迫既BigInteger然後:
    • 如果操作者是+,返回A.add(B)
    • 如果運營商是 - ,則返回A.subtract(B)
    • 如果運營商是*,則返回A.multiply(B)
  • A和B二者,否則脅迫到Long和應用操作者
  • 如果操作者造成的異常,錯誤

因此,是EL表達式#{bean.price * bean.currencyRate}"<h:outputText>指定,

<h:outputText value="#{bean.price * bean.currencyRate}"/> 

被評估爲java.math.BigDecimal,因爲bean.pricebean.currencyRate在相應的ba cking bean類型爲java.math.BigDecimal - bean.price.multiply(bean.currencyRate)在內部執行。