How to format numbers as percentages in Scala?
In this article, we will learn to format numbers as percentages in Scala using various methods such as f, %, and java.text.DecimalFormat. Formatting numbers as percentages that consist of representing numerical values as ratios out of 100, typically with a specific number of decimal places.
Example 1: In this example, we are using the ‘f’ method to format the number 0.75 as a percentage with two decimal places and printing the result in Scala.
// Creating object
object GFG {
def main(args: Array[String]): Unit = {
// Number input
val number = 0.75
// Formatting number as percentage
val res = f"${number * 100}%.2f%%"
// Printing Output
println(res)
}
}
Output:
75.00%
Example 2: In this example, we are using the %, method to format the number 0.75 as a percentage with two decimal places and printing the result in Scala.
// Creating object
object GFG {
def main(args: Array[String]): Unit = {
// Number input
val number = 0.75
// Formatting number as percentage
val res = "%.2f%%".format(number * 100)
// Printing Output
println(res)
}
}
Output:
75.00%
Example 3: In this example, we are using the java.text.DecimalFormat class to format the number 0.75 as a percentage with two decimal places and printing the result in Scala.
import java.text.DecimalFormat
// Creating Object
object GFG {
def main(args: Array[String]): Unit = {
// Number input
val number = 0.75
// Creating Decimal Format
val dFormat = new DecimalFormat("#.##'%'")
// Formatting number as percentage
val res = dFormat.format(number * 100)
// Printing Output
println(res)
}
}
Output:
75%
Contact Us