I need to convert a string to an integer. For example, I would like to convert sixth to 6.
I did the reverse one (6 → sixth) by using IBM's library ICU.
private val String.spellout: String
get() {
val esFormatter = RuleBasedNumberFormat(Locale.ENGLISH, RuleBasedNumberFormat.SPELLOUT)
return esFormatter.format(this.toDouble(), "%spellout-ordinal")
}
I would like to create another method that takes that spelled-out string and converts it to a double (sixth → 6)
After getting help from the comments here is my solution, in case anybody else needs it:
private val String.numberFromSpelledOut: Boolean
get() {
val esFormatter = RuleBasedNumberFormat(Locale.ENGLISH, RuleBasedNumberFormat.SPELLOUT)
return try {
return esFormatter.parse(this)
} catch (e: ParseException) {
""
}
}
This should not throw an exception for invalid spelled-out inputs.