Formatting Long and Double in Scala println

14.1k views Asked by At

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.

2

There are 2 answers

0
Puneeth Reddy V On

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

0
Grzegorz Kazior On

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