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.
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
).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With