1

I don't know if it's just me, but

<fmt:formatNumber var="roundedNumber" value="2.5" type="number" pattern="#" />

gives me

<%-- ${roundedNumber} == 2 --%>

Do you know why formatNumber doesn't round this to 3?

UPDATE

It seems that if the number is ODD is rounded correctly, but if it's even number it's not.

2.5 will be rounded 2
2.51 will be rounded 3
3.5 will be rounded 4
3.51 will be rounded 4
4.5 will be rounded 4
4.51 will be rounded 5
... etc
drinchev
  • 19,201
  • 4
  • 67
  • 93

1 Answers1

7

I thought the cause might be the implementation of the JSTL by the container but the same thing happens to me.

I then read the JavaServer Pages Standard Tag Library version 1.0 specifications and in section 9.7 fmt:formatNumber in the paragraph entitled Description it says that a pattern string specified via the pattern attribute must follow the pattern syntax specified by the class java.text.DecimalFormat.

So I looked up the java docs of java.text.DecimalFormat and in the section entitled Rounding it states that by default that it uses the RoundingMode.HALF_EVEN mode to round. This mode rounds a number towards the "nearest neighbour" unless both neighbours are equidistant, in which case, round towards the even neighbour.

This then explains why 2.5 rounds to 2 (the nearest even neighbour) and 3.5 rounds to 4 (the nearest even neighbour).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Alex Theedom
  • 1,604
  • 15
  • 16