This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

A question about formatNumber and decimal places

Thomas Kennedy
Ranch Hand
Posts: 137
I'm printing currency values to the screen using <fmt:formatNumber>. If my numeric value has a non-zero fractional part I want exactly two decimal places. If the fractional part is zero I want the decimal places omitted.

so 45.75 prints as \$45.75
but 201.00 prints as \$201

How can I do that?

Paul Clapham
Sheriff
Posts: 21443
33
So that means that 18.30 should print as \$18.30 and not as \$18.3? In that case I think you're going to need two different formatters and some kind if-then-else to distinguish the two cases. Writing a custom tag might be the right way to go here.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65278
95

Why two formatters? What are the two cases? I only see one.

No custom tag is necessary, the <fmt:formatNumber> tag should do just fine.

But the OP hasn't shown that any effort has been put into the problem yet. What formats have been tried that aren't working?

Paul Clapham
Sheriff
Posts: 21443
33
Thomas Kennedy wrote:If my numeric value has a non-zero fractional part I want exactly two decimal places.

If the fractional part is zero I want the decimal places omitted.

These are the two cases I saw. I don't see how to implement that with a single DecimalFormat.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65278
95
Ah. I thought that no-trailing was an undesirable outcome.

In that case, I'd simply use the ternary operator to choose between the two patterns.

Thomas Kennedy
Ranch Hand
Posts: 137
Is there anything in the fn library that can perform decision in a robust way? All I can think of is to check if the String representation of the value ends with ".00", and that sounds ugly. BTW does Oracle have a documentation page for EL? Thank you.

Paul Clapham
Sheriff
Posts: 21443
33

Paul Clapham
Sheriff
Posts: 21443
33
And no, there isn't an EL function in the fn: namespace which does that. But you don't need one, either. One of the EL operators is sufficient.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65278
95
What type is the numeric value? How would you test it in a Java expression to see if it were a whole number or not?

Thomas Kennedy
Ranch Hand
Posts: 137
In Java I would use Math.round() to compare the value to itself. So I could step out to a scriptlet but would prefer to avoid that.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 65278
95
OK, so let's say you've been forbidden to use the Math class. How would you do with basic operators?