Sunday, 16 August 2020

Scala: Formatting strings: printf notation

 Formatting strings can be created by prefixing the string with ‘f’.

 

Example

var PI = 3.1428571428

 

Now I can print value of PI to 3 decimal places using below formatted string.

f"Value of PI is $PI%.3f"

 

As you observe above snippet, formatting is specified using %.

scala> var PI = 3.1428571428
var PI: Double = 3.1428571428

scala> var msg1 = f"Value of PI is $PI%.3f"
var msg1: String = Value of PI is 3.143

scala> var msg2 = f"Value of PI is $PI%.6f"
var msg2: String = Value of PI is 3.142857

scala> 

scala> print(msg1)
Value of PI is 3.143
scala> 

scala> print(msg2)
Value of PI is 3.142857




Previous                                                    Next                                                    Home

No comments:

Post a Comment