實體中定義為Double型,如果為整數的話頁面上會顯示為XX.0
現要求整數的話顯示整數,小數的話顯示兩位小數(如1.0顯示為1,1.123顯示為1.12)
@Name("salaryValueConverter") @BypassInterceptors @org.jboss.seam.annotations.faces.Converter(id = "salaryValueConverter") public class SalaryValueConverter implements Converter { private static final String INTEGER_FORMATTER = "#,###";// 整型數據轉換后的格式 private static final String DOUBLE_FORMATTER = "#,###.##";// 浮點型數據轉換后的格式 private static final String EXCEPTION_MESSAGE = "請輸入數字格式!";// 格式轉換出錯提示信息 private static final String NULL_STRING = "";// 空字符串 /* * (non-Javadoc) * * @see * javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext * , javax.faces.component.UIComponent, java.lang.String) */ public Object getAsObject(FacesContext context, UIComponent component, String value) { // TODO Auto-generated method stub if (value.equals(NULL_STRING))// 如果value為空返回空值 return null; try { return Double.parseDouble(value.replace(",", NULL_STRING).trim()); } catch (NumberFormatException e) { // TODO: handle exception e.printStackTrace(); FacesMessages.instance().add(EXCEPTION_MESSAGE); return null; } } /* * (non-Javadoc) * * @see * javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext * , javax.faces.component.UIComponent, java.lang.Object) */ public String getAsString(FacesContext context, UIComponent component, Object value) { // TODO Auto-generated method stub DecimalFormat integerFormatter = new DecimalFormat(INTEGER_FORMATTER);// 整型轉換 DecimalFormat doubleFormatter = new DecimalFormat(DOUBLE_FORMATTER); // 浮點型轉換 if ((Double) value % 1 == 0) {// value為整數(如1或者1.0) return integerFormatter.format(value); } else {// value為小數(如1.1) return doubleFormatter.format(value); } } }
<h:inputText value="#{abc}" converter="salaryValueConverter" />