How to convert a string with either, or . as decimal/thousand separators into a float in Scala

1 Answer

0 votes
object LocalizedFloatParser {
  def toFloat(input: String): Double = {
    val commaCount = input.count(_ == ',')
    val dotCount = input.count(_ == '.')

    val lastComma = input.lastIndexOf(',')
    val lastDot = input.lastIndexOf('.')

    var str = input

    if (commaCount > 0 && dotCount > 0) {
      if (lastComma > lastDot) {
        str = str.replace(".", "").replace(",", ".")
      } else {
        str = str.replace(",", "")
      }
    } else if (commaCount > 0) {
      str = str.replace(".", "").replace(",", ".")
    } else {
      str = str.replace(",", "")
    }

    str.toDouble
  }

  def main(args: Array[String]): Unit = {
    println(f"${toFloat("1,224,533.533")}%.3f")
    println(f"${toFloat("1.224.533,533")}%.3f")
    println(f"${toFloat("2.354,67")}%.2f")
    println(f"${toFloat("2,354.67")}%.2f")
  }
}

 



answered Jun 27, 2025 by avibootz
...