fmt:formatNumber舍入不一致 [英] fmt:formatNumber rounding inconsistency

查看:178
本文介绍了fmt:formatNumber舍入不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否只有我,但是

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 syntax specified by the class java.text.DecimalFormat.

因此,我查找了 java的java文档. text.DecimalFormat 并在标题为 Rounding 的部分中指出,默认情况下,它使用

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舍入不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆