开发者

Why does JSTL output a double value of 99 as 99.0 (not 99.00) using ${dollarAmount}?

I have a double value dollarAmount which has the value 99:

double dollarAmount = 99;

When I try to output it to my page using this code:

开发者_JAVA技巧
<c:out value="${dollarAmount}"/>

It comes out as 99.0.

Because it represents a financial value, I want to output it either as

99

or as

99.00

Is there some way to force <c:out> to do this?


Why does JSTL output a double value of 99 as 99.0

When printing backend data to HTML response, all non-String java objects are by default converted to String. HTML can namely not be represented on other way. You're seeing 99.0, because that's the default result of Double#toString(double). The formatting is as per the documentation.

To format currencies, better use <fmt formatNumber> whose type is set to currency.

<fmt:formatNumber value="${dollarAmount}" type="currency" currencySymbol="$" />

It'll show up as

$99.00


i suggest the use of FormatNumber tag fmt

something like

<fmt:formatNumber type="number" maxIntegerDigits="2" value="${param.num}"/>


Use fmt:formatNumber


In java the best way to print out specific amounts of digits is printf, a third-party utility from https://sharkysoft.com/ available under the GNU GPL, or for a fee for commercial use. Here is the JavaDoc page: http://sharkysoft.com/archive/printf/docs/javadocs/lava/clib/stdio/doc-files/specification.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜