object SortDecimalStrings {
// Comparator function to sort strings as decimal numbers
def compareAsDecimal(a: String, b: String): Int = {
// Convert strings to float for comparison
val numA = a.toDouble
val numB = b.toDouble
numA.compareTo(numB)
}
def main(args: Array[String]): Unit = {
// Input array of strings
val numbers = Array("12.3", "5.6", "789.1", "3.14", "456.0", "0", "0.01", "4.0")
// Sort the array using the custom comparator
val sorted = numbers.sortWith((a, b) => compareAsDecimal(a, b) < 0)
println("Sorted array of decimal strings:")
for (num <- sorted) {
print(s"$num ")
}
}
}
/*
run:
Sorted array of decimal strings:
0 0.01 3.14 4.0 5.6 12.3 456.0 789.1
*/