Skip to content

Instantly share code, notes, and snippets.

@RotBolt
Created June 9, 2019 09:58
Show Gist options
  • Save RotBolt/f0ee4a262bf86a272a186420e7aae728 to your computer and use it in GitHub Desktop.
Save RotBolt/f0ee4a262bf86a272a186420e7aae728 to your computer and use it in GitHub Desktop.
private fun extractNumber(numString: String) = numString.toDoubleOrNull()
private fun isValue(expression: String): Boolean {
val validChars = "1234567890.-"
for (i in expression.indices) {
val char = expression[i]
if (char !in validChars) return false
if (expression.count { it == '.' } > 1) return false
if (char == '-' && i != 0) return false
}
return true
}
return when {
isValue(expression) -> extractNumber(expression) ?: Double.MIN_VALUE
expression == "PI" -> PI
expression == "E" -> E
else -> throw NumberFormatException()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment