我使用控件来获取输入作为印度货币.我期望的格式是##,##,###.##,但是我无法通过locale =’hi_IN’或pattern =’##,###.#来实现. #’.控件的值为double类型.
如果我将语言环境更改为“ hi_IN”,则数字将以默认的千位分隔符格式(#,###,###.##)在Devanagari中显示.
有没有办法实现INR格式?
最佳答案
基于this response to the pure Java variant of your problem,我使用com.ibm.icu.text.DecimalFormat组成了一个转换器:
package my.converter; import java.math.BigDecimal; import java.text.ParseException; import java.util.Locale; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; import com.ibm.icu.text.DecimalFormat; @FacesConverter("enhancedDecimalConverter") public class EnhancedDecimalConverter implements Converter<BigDecimal> { @Override public BigDecimal getAsObject(FacesContext context,UIComponent component,String value) { if (null == value) { return null; } DecimalFormat format = getFormatter(); BigDecimal result; try { result = BigDecimal.valueOf(format.parse(value).doubleValue()); } catch (ParseException e) { throw new ConverterException(e); } return result; } @Override public String getAsString(FacesContext context,BigDecimal value) { if (null == value) { return null; } DecimalFormat format = getFormatter(); String result = format.format(value); return result; } private DecimalFormat getFormatter() { return (DecimalFormat) DecimalFormat.getCurrencyInstance(getLocale()); } private Locale getLocale() { return FacesContext.getCurrentInstance().getViewRoot().getLocale(); } }
@H_404_15@在XHTML中的用法:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:p="http://primefaces.org/ui"> <h:head /> <h:body> <h:form> <p:inputText value="#{myBean.decimalVal}" converter="enhancedDecimalConverter"> </p:inputText> <h:panelGrid columns="2"> <h:outputText value="formatted: " /> <h:outputText value="#{myBean.decimalVal}" converter="enhancedDecimalConverter"> </h:outputText> <h:outputText value="raw: " /> <h:outputText value="#{myBean.decimalVal}"> </h:outputText> </h:panelGrid> <p:commandButton value="submit" process="@form" update="@form" /> </h:form> </h:body> </html>
@H_404_15@输出截图示例:
pom.xml中的Maven依赖关系:
<dependency> <groupId>com.ibm.icu</groupId> <artifactId>icu4j</artifactId> <version>64.1</version> </dependency>
@H_404_15@faces-config.xml中的示例语言环境配置:
<application> <locale-config> <default-locale>hi_IN</default-locale> </locale-config> </application>
@H_404_15@请注意,这里介绍的依赖项是12 MB的.jar,它的许可权是Unicode/ICU License.如果使用它,请确保它与您的项目兼容.