5

If you try the following bit you'll get -0

<c:set var="demo" value="-0.04" />
<fmt:formatNumber maxFractionDigits="1" value="${demo}" var="demo" />

but if you test if less than 0 it says true

<c:if test="${demo < 0.00}">...</c:if>

How can I go around this? It doesn't seem to make sense, 0 equals -0, I had the prove it in algebra... In this post they point to an IEEE reference, but still, I can't solve the problem

EDIT: Thanks for the comment, there as a mistake in the code sample. I assign the rounded value to the demo variable. And the output is not 0, but -0, I tried it

Community
  • 1
  • 1
Hartimer
  • 525
  • 6
  • 20
  • What's the issue? You've assigned a variable a value of-0.04, and then you output it, rounded to one decimal place (which will output 0.0). Then you test if the original value, -0.04 is less than 0.00... which yields true. – patros Aug 29 '12 at 19:00
  • 1
    There was a mistake in the code, fixed it. And it does NOT output 0, outputs -0 – Hartimer Aug 29 '12 at 20:58
  • 1
    Dibs for 'Negative Zero' as band name! – Karl-Bjørnar Øie Aug 29 '12 at 20:58
  • @ZeroPage http://www.negativezero.org/ – Dave Newton Aug 29 '12 at 21:41
  • @DaveNewton awwww... :-) – Karl-Bjørnar Øie Aug 29 '12 at 21:46
  • That does seem to be an oversight in the formatting code, . General arithmetic usually returns a positively signed integer. After doing the round I would try – patros Aug 29 '12 at 22:21
  • "It doesn't seem to make sense, 0 equals -0," -- Just as a counterexample, for temperatures in degrees Celsius, -0 means it's freezing. Plain 0 or +0 (used interchangeably) means it isn't. -0.1 is intentionally not rounded to +0 in that case. –  Aug 30 '12 at 11:06

3 Answers3

0

Long shot here, but is it because it is parsing the original -0.04 as a string?

Maybe try this, which I think will force it to evaluate as a number:

<c:set var="demo" value="${-0.04}" />
Stewart
  • 17,616
  • 8
  • 52
  • 80
0

OK, this time I think I can explain it: it's a bug (or feature) of java.text.DecimalFormat, which is what <fmt:formatNumber /> uses under the bonnet.

Here is a copy'n'paste of a quick Beanshell session I tried as an experiment:

BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % import java.text.*;
bsh % fmt = new DecimalFormat();
bsh % fmt.setMaximumFractionDigits(1);
bsh % print(fmt.format(-0.04d));
-0
bsh % 
Stewart
  • 17,616
  • 8
  • 52
  • 80
0

You could write your own number formatting tag which compensates this.

// Read these values from tag attributes
String pattern = "0";
Double myNumber = -0.04d;

// Create a decimal format with correct rounding
DecimalFormat df = new DecimalFormat(pattern);
df.setRoundingMode(RoundingMode.HALF_UP);

// Format in two steps to compensate for '-0'
String temp = df.format(myNumber + 1);
String formatted = df.format(Double.valueOf(temp) - 1);
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102