Formatting Long and Double in Scala println

10,435

Solution 1

In Scala we write

val height = 1.9d
val weight = 100L
val name = "James"
println(f"$name%s is $height%2.2f meters tall and weights $weight%3d kg")  // James is 1.90 meters and weights 100 kg

Solution 2

Here is how you can format in println statement we can use String.format() method to format, as shown below

var LONG : Long = 9L;
println("The value of LONG is %d\n".format(LONG))
var DOUBLE : Double = 9.9;
printf("The value of DOUBLE is %.2f".format(DOUBLE));

results you :-

The value of LONG is 9

The value of DOUBLE is 9.90

For more options on formatting flags refer to http://web.cerritos.edu/jwilson/SitePages/java_language_resources/Java_printf_method_quick_reference.pdf

Share:
10,435
Jes
Author by

Jes

Updated on June 27, 2022

Comments

  • Jes
    Jes almost 2 years

    What's the suffix after '%' I should use in order to format a Long or a Double type variables?

    var LONG : Long = 9L;
    println("The value of LONG is %?".format(LONG));
    var DOUBLE : Double = 9.9;
    println("The value of DOUBLE is %?".format(DOUBLE));
    

    Many thanks.