Reputation: 187399
I've noticed some strange behaviour when resolving Grails messages using the g.message
tag. In my properties file I've defined this message:
deleted={0} has been deleted
If I resolve this with:
Long id = 1878L
message(code: 'festival.deleted', args: [id.toString()])
the result is:
1878 has been deleted
which is what I would have expected. However, if I resolve it with:
Long id = 1878L
message(code: 'festival.deleted', args: [id])
the result is:
1,878 has been deleted
It's not clear to me why the number is formatted as "1,878" before it's substituted into the message. I thought perhaps toString()
is called on all message arguments if they're not already of type String
, but this doesn't appear to explain this behaviour, because
id.toString() == "1878"
Upvotes: 3
Views: 675
Reputation: 19702
The g.message
tag uses Java's MessageFormat to generate the text output. MessageFormat has several default ways of formatting arguments if no argument format is specified. {0} has been deleted
says there's an argument but doesn't say how to format it.
If the argument is a String, the string is inserted into the message. If the argument is a Number, NumberFormat is used.
groovy:000> NumberFormat.getInstance().format(1878L)
===> 1,878
There's a nice table in the docs for format()
that breaks down what happens in what cases. If you want to use a Long as your argument without calling toString()
on it, you can change your argument to {0,number,#}
which would be equivalent to
groovy:000> new DecimalFormat("#", DecimalFormatSymbols.getInstance()).format(1878L)
===> 1878
Upvotes: 2