Open In App

How to format numbers as percentages in Scala?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

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.

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%

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads