Skip to content

Instantly share code, notes, and snippets.

@mutkuensert
Last active July 20, 2023 15:27
Show Gist options
  • Save mutkuensert/6978169e26d68880b8235f4b1d36124a to your computer and use it in GitHub Desktop.
Save mutkuensert/6978169e26d68880b8235f4b1d36124a to your computer and use it in GitHub Desktop.
String to double converter extension function
fun String.convertToDouble(): Double {
val newValue: String = this.replace(",", ".")
var withoutExtraDots = ""
var indexOfFirstDot: Int? = null
var index = 0
for (c in newValue) {
if (index == 0 && c == '.') return 0.0
if (indexOfFirstDot == null && c == '.') indexOfFirstDot = index
withoutExtraDots += if (c == '.' && index != indexOfFirstDot) {
continue
} else {
c
}
index += 1
}
return withoutExtraDots.toDouble()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment