Sunday, June 29, 2014

format number with spaces thouthands separator

Nowhere could I find it. I therefore implemented mine own method (using flatMap) and practicing some Scala. Here is mine try (scastie)

def format(n: Long): String = {
 (n.toString.reverse.grouped(3).flatMap(s => ' ' + s) mkString "").reverse.trim
} //> format: (n: Long)String

format(1) //> res0: String = 1
format(12) //> res1: String = 12
format(123) //> res2: String = 123
format(1234) //> res3: String = 1 234
format(123444444) //> res4: String = 123 444 444

You can also format numbers online

No comments: