Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a double without decimals & adding commas for thousands in Scala Java Play framework

I have doubles such as:

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",""))

This was with the help of:

how to format a number/date in play 2.0 template?

What is the proper way to format a double in a Play 2 template


I'd like to replace this shameless solution by something more clean. Chopping off those decimals using a .replace() method is really not pretty.

like image 947
Adrien Be Avatar asked Aug 31 '25 06:08

Adrien Be


2 Answers

The "2" in %,.2f represents the number of decimals to use in the formatting. You could just use %,.0f instead:

"%,.0f".format(myDoubleHere)  

You can read more about Java formatting in the docs here. Your other option is to round to an Int, and then use %,d:

"%,d".format(math.round(myDoubleHere))

This might handle some edge cases better, depending on your use-case (e.g. 5.9 would become 6 and not 5).

like image 186
Ben Reich Avatar answered Sep 02 '25 20:09

Ben Reich


Best understood through simple examples, use %,d:

scala> f"Correctly Formatted output using 'f': ${Int.MaxValue}%,d"
val res30: String = Correctly Formatted output using 'f': 2,147,483,647

scala> s"Incorrectly Formatted output using 's': ${Int.MaxValue}%,d"
val res31: String = Incorrectly Formatted output using 's': 2147483647%,d
like image 22
Saurav Sahu Avatar answered Sep 02 '25 20:09

Saurav Sahu