- Learning Scala Programming
- Vikash Sharma
- 119字
- 2025-04-04 17:32:11
f Interpolator
To have something like printf styled formatting in Scala, we can use the f interpolator. We do this by using a f preceding the double quotes of our string, and then within the String we can use one of the format specifiers:
scala> val amount = 100
amount: Int = 100
scala> val firstOrderAmount = f"Your total amount is: $amount%.2f"
firstOrderAmount: String = Your total amount is: 100.00
From the preceding example, it's clear that we use f as a prefix to our string and use $ followed by the expression that includes our format specifier. This works as a formatter for our strings.
A few format specifiers are listed as following:

Format Specifiers