我有一个由用户输入的金额,我想验证它。我已经编写了一个 JSF validator ,但在所有情况下都无法让它正常工作。这是我的场景:
我有不同区域设置的用户,因此我需要处理各种输入方法,并希望允许以下内容
English
1234
1,234
1234.56
1,234.5
German & Spanish
1234
1.234
1234,56
1.234,5
French
1234
1 234
1234,56
1 234,5
我的问题是法语,因为使用此代码时选项 2 和 4 被视为无效,因为解析在空格处停止。
public void validate(final FacesContext pContext,
final UIComponent pComponent,
final Object pValue) {
boolean isValid = true;
final Locale locale = (Locale)pComponent.getAttributes().get(USERS_LOCALE);
final Currency currency = (Currency)pComponent.getAttributes().get(CURRENCY);
final NumberFormat formatter = NumberFormat.getNumberInstance(locale);
formatter.setGroupingUsed(true);
formatter.setMinimumFractionDigits(currency.getDefaultFractionDigits());
formatter.setMaximumFractionDigits(currency.getDefaultFractionDigits());
final ParsePosition pos = new ParsePosition(0);
final String stringValue = (String)pValue;
if (pos.getIndex() != stringValue.length() || pos.getErrorIndex() != -1) {
isValid = false;
}
...
我还想确保以下内容被视为无效但它们都解析成功(当然除了法语)
1,234,9.56(无效分组)
1,234.567(货币的小数位太多)
任何帮助将不胜感激
伊恩
最佳答案
法语千位分隔符实际上是一个不间断的空格,\u00a0
。如果您的输入使用常规空格,您可以更改输入:
input = input.replace(' ', '\u00a0');
您可以做的另一件事是将分组符号更改为常规空格:
DecimalFormat decimalFormatter = (DecimalFormat) formatter;
DecimalFormatSymbols symbols = decimalFormatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
decimalFormatter.setDecimalFormatSymbols(symbols);
不过,不能推荐这个。新的格式化程序不接受使用不间断空格作为分组字符的数字。
关于java - NumberFormat 本地化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9621322/