【问题标题】:NumberFormat localization issuesNumberFormat 本地化问题
【发布时间】:2012-03-26 03:39:10
【问题描述】:

我有一个由用户输入的金额并想要验证它。我已经编写了一个 JSF 验证器,但在所有情况下都无法让它工作。这是我的场景:
我有不同区域的用户,因此我需要处理各种输入方法并希望允许以下操作

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(货币的小数位数太多)

任何帮助将不胜感激
伊恩

【问题讨论】:

    标签: java localization number-formatting jsf-1.2


    【解决方案1】:

    法国千位分隔符实际上是一个不间断的空格,\u00a0。如果您的输入使用常规空格,您可以更改输入:

    input = input.replace(' ', '\u00a0');
    

    您可以做的另一件事是将分组符号更改为常规空格:

    DecimalFormat decimalFormatter = (DecimalFormat) formatter;
    DecimalFormatSymbols symbols = decimalFormatter.getDecimalFormatSymbols();
    symbols.setGroupingSeparator(' ');
    decimalFormatter.setDecimalFormatSymbols(symbols);
    

    不过,不能推荐这个。新的格式化程序不接受使用不间断空格作为分组字符的数字。

    【讨论】:

    • 谢谢,学到了新东西。更多关于此的讨论可以在 oracle 的错误跟踪器上找到:bugs.sun.com/view_bug.do?bug_id=4510618
    • 感谢您的回复,第一个确实有效,尽管我使用 stringValue.replace(' ', symbols.getGroupingSeparator()) 而不是硬代码
    • 关于无效分组和小数位的第二部分有人帮忙吗? (可能应该将此作为一个单独的问题!)
    • 第二部分你可能需要正则表达式,解析时 NumberFormat 不强制格式。例如。对于大于 1 的金额,需要两位小数,[1-9]\d{0,2}(?:,\d{3})*\.\d{2} 应该可以。
    • 再次感谢 Joni,会试一试
    猜你喜欢
    • 2015-05-05
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2011-07-11
    • 2011-02-23
    相关资源
    最近更新 更多