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.

+3


source to share


3 answers


"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

).

+2


source


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

      

0


source


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

      

0


source







All Articles