Formatting double without decimal places and adding commas for thousands in Scala Java Play framework

I have a doubling for example:



I want to output them as:



I found the following solution:



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

3 answers

"2" in %,.2f

represents the number of decimal places to use in formatting. You can use instead %,.0f




More on Java formatting in the docs here . Another option is to round up to Int

and then use %,d




This may cause some edges to be better, depending on your use case (e.g. 5.9

become 6

, not 5




Using Java DecimalFormat

, we have that

val df = new java.text.DecimalFormat("###,###");
df: java.text.DecimalFormat = java.text.DecimalFormat@674dc


and therefore

scala> df.format(87654783927493.00)
res: String = 87,654,783,927,493

scala> df.format(23648.00)
res: String = 23,648




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




All Articles