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

Here, we will see Scala implementation of formatting of string and adding % for printing sequence in a specific format.
Submitted by Shivang Yadav, on January 04, 2021

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.

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.

Program to illustrate the working of our solution

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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.