Java NumberFormat with equivalent negative and pos

2019-09-17 20:44发布

I want to format a number without any prefix (or the same prefix) for both positive and negative numbers.

The specification of NumberFormat states that you can specify a sub pattern for positive numbers and a sub pattern for negative numbers, separated by a semicolon.

Each subpattern has a prefix, numeric part, and suffix. The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign ('-' in most locales) is used as the negative subpattern. That is, "0.00" alone is equivalent to "0.00;-0.00".

This works, as long as the positive and negative sub patterns have distinct prefixes or suffixes. If they are the same, it defaults to the default behavior with a minus sign.

What I want is to format:

  • +1 as :01
  • -1 as :01

I know that I can use Math.abs(), which is not so easy in a JSP/EL environment and it's a pure formatting issue, so should be done in JSP, but that's not the point at all. I couldn't find any hint in the documentation about that behavior. When I read the above, I think that as soon as I specify any negative sub pattern, it will be used. Which is not the case.

Does anyone know something about this? I might file a bug with Oracle, but wanted to check first, if I'm missing something.

2条回答
疯言疯语
2楼-- · 2019-09-17 20:50

Assuming you have JSTL in your wepapp, you could use the following:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<fmt:formatNumber pattern=":#" minIntegerDigits="2" value="${fn:replace('-1', '-', '')}" />

Hope this help...

查看更多
放我归山
3楼-- · 2019-09-17 20:57

Not sure what exactly your format is supposed to be, but this seems to work for your example:

DecimalFormat f = new DecimalFormat(":00");
f.setNegativePrefix(":");
System.out.println(f.format(1));  // :01
System.out.println(f.format(-1)); // :01 
查看更多
登录 后发表回答