Search code examples
scalastring-formattingdataformat

Most efficient way to format a string in scala with leading Zero's and a comma instead of a decimal point


Trying to create a simple function whereby a String value is passed in i.e. "1" and the formatter should return the value with leading zeros and 5 decimal points however instead of a dot '.' I'm trying to return it with a comma ','

This is what I have attempted however its not working because the decimalFormatter can only handle numbers and not a string. The end goal is to get from "1" to "000000001,00000" - character length is 14 in total. 5 0's after the comma and the remaining before the comma should be padded out 0's to fill the 9 digit requirement.

Another example would be going from "913" to "000000913,00000"

 def numberFormatter (value: String): String =
{
     import java.text.DecimalFormat
     val decimalFormat = new DecimalFormat("%09d,00000")
     val formattedValue = decimalFormat.format(value)
     return formattedValue
}

Any help would be much appreciated. Thank you in advance.


Solution

  • It's easy enough to format a String padded with spaces, but with zeros not so much. Still, it's not so hard to roll your own.

    def numberFormatter(value :String) :String =
      ("0" * (9 - value.length)) + value + ",00000"
    
    numberFormatter("1")    //res0: String = 000000001,00000
    numberFormatter("913")  //res1: String = 000000913,00000
    

    Note that this won't truncate the input String. So if value is longer than 9 characters then the result will be longer than the desired 15 characters.