问题描述
我不知道是否只有我,但是
I don't know if it's just me, but
<fmt:formatNumber var="roundedNumber" value="2.5" type="number" pattern="#" />
给我
<%-- ${roundedNumber} == 2 --%>
您知道为什么formatNumber不能将其四舍五入吗?
Do you know why formatNumber doesn't round this to 3?
更新
似乎如果ODD的数字正确舍入,但是即使是偶数也不正确.
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
推荐答案
我认为原因可能是容器对JSTL的实现,但我也遇到了同样的事情.
I thought the cause might be the implementation of the JSTL by the container but the same thing happens to me.
然后,我阅读 JavaServer Pages标准标记库版本1.0 规范,并在描述的段落中,strong>第9.7节fmt:formatNumber 指出,通过pattern属性指定的模式字符串必须遵循模式语法由类java.text.DecimalFormat指定.
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 syntaxspecified by the class java.text.DecimalFormat.
因此,我查找了 java的java文档. text.DecimalFormat 并在标题为 Rounding 的部分中指出,默认情况下,它使用 RoundingMode.HALF_EVEN 模式进行舍入.除非两个邻居都是等距的,否则此模式会将数字四舍五入为最近的邻居",在这种情况下,将四舍五入为偶数邻居.
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.
然后,这说明了为什么2.5舍入到2(最近的偶数邻居)和3.5舍入到4(最近的偶数邻居).
This then explains why 2.5 rounds to 2 (the nearest even neighbour) and 3.5 rounds to 4 (the nearest even neighbour).
这篇关于fmt:formatNumber舍入不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!