數字格式轉換器

實體中定義為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" />

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值