0

I'm a new learner of spark. There's one line of code estimating pi but I don't quite understand how it works.

scala>val pi_approx = f"pi = ${355f/113}%.5f"
pi_approx: String = pi = 3.14159

I don't understand the 'f' '$' and '%' in the expression above. Could anyone explain the usage of them? Thanks!

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
  • 1
    its just formating the number . 355f is a float number devided by 113 . .5f denotes to show until five decimal places. $ to match the floating number and f in the front denote the floating number denoted by $ inside "" string for more info read https://docs.scala-lang.org/overviews/core/string-interpolation.html – Ramesh Maharjan Mar 09 '18 at 02:26
  • Thanks! It's very helpful! ^^ – user8393141 Mar 09 '18 at 02:59
  • Possible duplicate of [Better String formatting in Scala](https://stackoverflow.com/questions/4051308/better-string-formatting-in-scala) – philantrovert Mar 09 '18 at 07:01

1 Answers1

1

This is the example of String Interpolation that allows users to embed variable references directly in processed string literals. For e.g.

scala> val name = "Scala"
name: String = Scala

scala> println(s"Hello, $name")
Hello, Scala

In above example the literal s"Hello, $name" is a processed string literal.

Scala provides three string interpolation methods out of the box: s, f and raw. Prepending f to any string literal allows the creation of simple formatted strings, similar to printf in other languages.

The formats allowed after the % character tells that result is formatted as a decimal number while ${} allows any arbitrary expression to be embedded. For e.g.

scala> println(s"1 + 1 = ${1 + 1}")
1 + 1 = 2

More detailed information can be found on:

Ayush Vatsyayan
  • 2,498
  • 21
  • 27