Formatting double without decimal places and adding commas for thousands in Scala Java Play framework
I have a doubling for example:
87654783927493.00
23648.00
I want to output them as:
87,654,783,927,493
23,648
I found the following solution:
@("%,.2f".format(myDoubleHere).replace(".00",""))
It was with:
how to format number / date pattern in game 2.0?
What is the correct way to format the double in the Play 2 template
I would like to replace this shameless solution with something cleaner. Disabling those decimal places with the method .replace()
really isn't pretty.
source to share
"2" in %,.2f
represents the number of decimal places to use in formatting. You can use instead %,.0f
:
"%,.0f".format(myDoubleHere)
More on Java formatting in the docs here . Another option is to round up to Int
and then use %,d
:
"%,d".format(math.round(myDoubleHere))
This may cause some edges to be better, depending on your use case (e.g. 5.9
become 6
, not 5
).
source to share
For integers and numbers, this works for me in regular Scala:
// get java number formatters
val dformatter = java.text.NumberFormat.getIntegerInstance
val fformatter = java.text.NumberFormat.getInstance
val deciNum = 987654321
val floatNum = 12345678.01
printf("deciNum: %s\n",dformatter.format(deciNum))
printf("floatNum: %s\n",fformatter.format(floatNum))
And the output is:
deciNum: 987,654,321
floatNum: 12,345,678.01
source to share