fmt:formatNumber rounding inconsistency

こ雲淡風輕ζ 提交于 2019-12-18 07:14:36

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/19313022/fmtformatnumber-rounding-inconsistency

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!