×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to use java.String.format() in Scala for formatting string?

By IncludeHelp Last updated : October 20, 2024

Scala programming language has a huge library that supports the working data types. For string also there are methods in Scala to support its functioning.

For string, one common usage is related to printing results of the program. Now for this many times, there are a lot of constraints needed to be attached with the string printing the result. Values are needed to be added to the string.

Use java.String.format() in Scala for formatting string

For doing this formatting work scala provides two methods:

  • format()
  • formatted()

And the % escape sequence is utilized to format strings. It acts as a placeholder which will afterward be replaced by the desired value.

Here, are some data type that can be defined using %,

  • %d : inserting integer values
  • %f : inserting float and double values
  • %c : inserting character values
  • %s : inserting string values

With these placeholders, we can use the formatting method for formatting the string in Scala.

Example of formatting string using java.String.format()

object MyClass {
    def main(args: Array[String]) {
        var output = "%s earns %.2f in a month!"
        var employee_name = "Manju"
        var employee_salary = 400000.00
        var formatted_string = output.format(employee_name, employee_salary)   
    
        print(formatted_string)
    }
}

Output

Manju earns 400000.00 in a month!

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.