【问题标题】:binding @NumberFormat , set comma as decimal separator?绑定 @NumberFormat ,设置逗号作为小数点分隔符?
【发布时间】:2012-09-05 08:38:44
【问题描述】:

我的问题是我从数据库中读取数字 (BigDecimal) 并使用 DOT 作为小数分隔符来查看它们,但我想使用 COMMA 来查看它们。我使用了以下代码:
@NumberFormat (style = Style.NUMBER, pattern = "##,###,###.##")
私人 BigDecimal 数字;

我的应用程序具有以下架构:
oracle db - hibernate - spring mvc

我需要自动转换,无需手动转换为带 DecimalFormat 的字符串。

【问题讨论】:

    标签: oracle hibernate spring-mvc


    【解决方案1】:

    我是这样解决的:

    @InitBinder
    public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {  
        DecimalFormat df =new DecimalFormat();  
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();  
        dfs.setDecimalSeparator(',');  
        df.setGroupingUsed(false);  
        df.setDecimalFormatSymbols(dfs);  
        df.setMaximumFractionDigits(32);  
        df.setMaximumIntegerDigits(32);  
        binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class,df, true));
    }
    

    【讨论】:

      【解决方案2】:

      类似于@Tostis 的解决方案,但使用全局应用的@InitBinder:

      @ControllerAdvice
      public class GlobalBindingInitializer {
      
        @InitBinder
        public void initBigDecimalBinder(WebDataBinder binder) throws Exception {
          DecimalFormat df = new DecimalFormat();
          DecimalFormatSymbols dfs = new DecimalFormatSymbols();
          dfs.setGroupingSeparator(',');
          df.setDecimalFormatSymbols(dfs);
          binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, df, true));
        }
      }
      

      【讨论】:

        【解决方案3】:

        BigDecimal 是 BigDecimal。它没有任何内在格式。

        此外,绝对不是像 Hibernate 这样的 ORM 的工作是按照您想要的方式转换数据。将您的实体视为数据,并在需要显示数据时在表示层中使用适当的 NumberFormat。数字格式化与持久层无关。

        编辑:我误解了这个问题:

        NumberFormat 取决于语言环境。这意味着, 表示“与区域设置关联的组分隔符”,'.' 表示“与区域设置关联的小数分隔符”。

        如果您希望将点作为组分隔符,将逗号作为小数分隔符,请使用默认将这些作为分隔符的区域设置,或者使用 DecimalFormat 和 set the DecimalFormatSymbols 来设置适当的值。

        【讨论】:

        • 我已经知道你说了什么,但我在问我应该在我的情况下使用什么模式。如果模式是##,###,###.## 我得到 99,999,999.99 但我想要 99.999.999,99
        • 对不起。我误解了这个问题。请查看我的答案中的修改。
        猜你喜欢
        • 2014-03-16
        • 1970-01-01
        • 2013-02-19
        • 1970-01-01
        • 2017-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多