本文介绍了convertNumber将0,00显示为负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试显示小于0的数字时,如下所示:

When I try to show a number less than 0 like this:

<p:column headerText="value">
    <h:outputText value="-0,000001">
        <f:convertNumber maxFractionDigits="2" minFractionDigits="2"
            type="number" />
    </h:outputText>
</p:column>

它显示-0,00

我需要将数字显示为0.00而不是-0.00

I need to show the number as 0.00 not as -0.00

如何解决此错误?

有人知道吗?

推荐答案

这确实是指定的行为.这不完全是JSF的错. <f:convertNumber> 使用 java.text.NumberFormat 的封面是只是标准Java SE的一部分.无法通过某种神奇的NumberFormat模式或属性来克服这一问题.您真的需要求助于字符串匹配和操作.

This is indeed specified behavior. This is not exactly JSF's fault. The <f:convertNumber> uses java.text.NumberFormat under the covers for the job which is just part of standard Java SE. There's no way to overcome this by some magic NumberFormat pattern or property. You'd really need to resort to string matching and manipulation.

给出以下功能要求:

解决方案是创建一个自定义转换器,以扩展JSF的 NumberConverter 并使用必要的字符串匹配和操作作业覆盖其getAsString():

The solution is to create a custom converter which extends JSF's NumberConverter and overrides its getAsString() with the necessary string matching and manipulation job:

@FacesConverter("customNumberConverter")
public class CustomNumberConverter extends NumberConverter {

    public CustomNumberConverter() {
        setMinFractionDigits(2);
        setMaxFractionDigits(2);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        String converted = super.getAsString(context, component, value);

        if (converted.charAt(0) == '-' && converted.replaceAll("[^0-9]", "").matches("0+")) {
            return converted.substring(1);
        }
        else {
            return converted;
        }
    }

}

将按以下方式使用(请注意,您不能在单个组件上指定多个转换器,这也是我接管最初在<f:convertNumber>上设置的属性的原因):

Which is to be used as follows (note that you cannot specify multiple converters on a single component, that's also why I took over the properties you initially set on <f:convertNumber>):

<h:outputText value="#{-0.000001}" converter="customNumberConverter" />

(请注意,我以有效的double语法(以句点作为小数分隔符)将硬编码数字值放在EL表达式中;否则将其视为String而不是Number;它是只能用于bean属性).

(note that I placed the hardcoded number value in valid double syntax (with period as fraction separator) in an EL expression; it's otherwise treated as a String instead of as Number; it'll just work for bean properties).

这篇关于convertNumber将0,00显示为负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:23