Issue
In Kotlin there is a shortcut for parsing an Int from a String:
"10".toInt()
However, if the number has a comma inside, e.g. "1,000".toInt(), it throws a NumberFormatException. I know I can use NumberFormat and Locale in Java to parse the number out. However, I wonder if there is a shortcut version for this in Kotlin.
Solution
Following the NumberFormat documentation, you can use NumberFormat to parse strings as well:
val numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH) as DecimalFormat
println(numberFormat.parse("1,000"))
>>> 1000
There is no shortcut in Kotlin. You have to specify the locale somewhere in order for Kotlin to know what the , means. It could be either a thousand separator - as in English - or a decimal point, as in German:
val numberFormat = NumberFormat.getNumberInstance(Locale.GERMAN) as DecimalFormat
println(numberFormat.parse("1,000"))
>>> 1
Answered By - Abby
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.