Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

jsp - fmt:formatNumber rounding inconsistency

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...