Horje
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.

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%



Reffered: https://www.geeksforgeeks.org


Scala

Related
How to check scala version on different OS? How to check scala version on different OS?
How to check String is null in Scala? How to check String is null in Scala?
How to connect MySQL database using Scala? How to connect MySQL database using Scala?
How to Merge Two Lists and Remove Duplicates in Scala? How to Merge Two Lists and Remove Duplicates in Scala?
How to Escape Double Quotes in Scala? How to Escape Double Quotes in Scala?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13