Last active
July 20, 2023 15:27
-
-
Save mutkuensert/6978169e26d68880b8235f4b1d36124a to your computer and use it in GitHub Desktop.
String to double converter extension function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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