java JSTL 舍入/向下数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11069697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSTL Round off/down number
提问by user1386375
This might be a dumb question, but let's say I have a variable seconds
in my JSP page and its value is 779. Now I want to convert it into minutes and seconds by doing the following:
这可能是一个愚蠢的问题,但假设seconds
我的 JSP 页面中有一个变量,其值为 779。现在我想通过执行以下操作将其转换为分钟和秒:
<c:set var="${seconds / 60}" value="min"/>
<c:set var="${seconds mod 60}" value="sec">
This way I get min = 12.983333 and sec = 59.0.
这样我得到 min = 12.983333 和 sec = 59.0。
Now I want to merge the two and display the result as 12:59. The problem I am facing is that min
keeps getting rounded up to 13. I have tried many things, such as:
现在我想合并两者并将结果显示为 12:59。我面临的问题是min
不断四舍五入到 13。我尝试了很多东西,例如:
<fmt:parseNumber var="minutes" integerOnly="true" type="number" value="${min}" />
<fmt:formatNumber type="number" pattern="###" value="${min}" var="minutes" />
fn:substringBefore(min, '.')
maxFractionDigits="0"
// and so on...
But all of them just return 13 consistently. I am a bit clueless at this point. But I may have missed something. I hope someone here has an idea, or a hint, about what might be wrong.
但他们都只是一致地返回 13。在这一点上,我有点不知所措。但我可能错过了一些东西。我希望这里有人对可能出现的问题有想法或提示。
-edit
-编辑
The code below made it work in the end. I have no clue what was wrong, since its also working with "/" now. Maybe some minor mistake elsewhere. Nevertheless thanks a lot for your time :) Kudos!
下面的代码使它最终工作。我不知道出了什么问题,因为它现在也使用“/”。也许其他地方的一些小错误。不过非常感谢您的时间:) 荣誉!
<c:set var="min" value="${fn:substringBefore((seconds div 60), '.')}"/>
<fmt:formatNumber var="sec" pattern="##" value="${seconds mod 60)}"/>
回答by Serge Miche9
This (below) should be the only safe way to do it. pattern="##" is not well supported, minIntegerDigits="2" is easier and cleaner.
这(下面)应该是唯一安全的方法。pattern="##" 没有得到很好的支持, minIntegerDigits="2" 更容易和更干净。
<c:set var="minutes" value="${fn:substringBefore(seconds div 60, '.')}"/>
<fmt:formatNumber var="seconds" minIntegerDigits="2" value="${ seconds - (minutes*60) }"/>
回答by buc
Use integral division to get the value for min
, instead of floating point division:
使用整数除法来获取 的值min
,而不是浮点除法:
<c:set var="min" value="${seconds div 60}" />
Now you get min = 12, and you don't have to worry about the rounding issues.
现在您得到 min = 12,并且您不必担心舍入问题。