Number formatting

@ val pi = scala.math.Pi 
pi: Double = 3.141592653589793

@ f"$pi%012.2f" 
res23: String = "000000003.14"

@ val d = 2 
d: Int = 2

@ f"$pi%012.${d}f" 
cmd25.sc:1: Missing conversion operator in '%012'; use %% for literal %, %n for newline
val res25 = f"$pi%012.${d}f"
                 ^
Compilation Failed

How do i use a variable to specify format string?

I don’t think this is possible using the f-Interpolator. You could use the simple s-Interpolator to build your format string and pass the actual values by calling format manually:

@ s"%012.${d}f".format(pi)
res5: String = "000000003.14"
1 Like

Thanks. That sure works.