How to format a number to a string in Scala

How can I format a floating variable like %6.2f would do in printf (C) and store the result in a string variable?

Upvotes: 0

Views: 337

Answers (1)

jwvh
jwvh

Reputation: 51271

Here's a floating point (Double) value and a handful of String format options via string interpolation.

val d = 12345.678

f"|$d%f|${-d}%f|"             // |12345.678000|-12345.678000|
f"|$d%+f|${-d}%+f|"           // |+12345,678000|-12345,678000|
f"|$d% f|${-d}% f|"           // | 12345,678000|-12345,678000|
f"|$d%.2f|${-d}%.2f|"         // |12345,68|-12345,68|
f"|$d%,.2f|${-d}%,.2f|"       // |12,345.68|-12,345.68|
f"|$d%.2f|${-d}%(.2f|"        // |12345,68|(12345,68)|
f"|$d%10.2f|${-d}%10.2f|"     // |  12345,68| –12345,68|
f"|$d%010.2f|${-d}%010.2f|"   // |0012345,68|-012345,68|

Upvotes: 3

Related Questions