Android Studio中Kotlin调用toDouble()转换有效数字字符串时抛出NumberFormatException问题排查
Hey there! Let's break this down for you clearly:
首先回答你的第一个问题:"3.00"是有效的数字表示吗?
Absolutely yes! In standard Kotlin/Java, "3.00".toDouble() should work flawlessly without throwing any exceptions—this is a completely valid decimal number string. The issue isn't with the string itself, it's rooted in how your app is handling the input based on device settings or hidden edge cases.
为什么会触发NumberFormatException?
The most common reason here is device locale (regional settings):
- Many regions (like Germany, France, etc.) use a comma
,as the decimal separator instead of a dot.. If your device's system locale is set to one of these regions, the defaulttoDouble()method will expect a comma instead of a dot. So when you input "3.00", it sees the dot as an invalid character and throws the exception. - Other less likely but possible causes:
- Hidden whitespace or invisible characters in the EditText input (like leading/trailing spaces, line breaks) that aren't visible but are present in the actual string.
- Accidental conflicting settings on your EditText's
inputType(double-check there's no other input type flags overridingnumberDecimal).
解决方案
Here are practical fixes you can implement right away:
1. Force a locale that uses dot as decimal separator
Use Kotlin's toDouble(Locale) extension function (available since Kotlin 1.3) to explicitly parse the string with a locale that uses dot for decimals, like Locale.US:
val inputText = etProduktGekauftPreis.text.toString().trim() val preis = try { inputText.toDouble(Locale.US) } catch (e: NumberFormatException) { // Show user feedback, e.g. a toast message Toast.makeText(this, "Please enter a valid decimal number", Toast.LENGTH_SHORT).show() 0.0 // Fallback value if parsing fails } val produkt = Produkt(name, anzahl.toInt(), preis)
2. Use NumberFormat for locale-aware parsing
If you want to support both dot and comma based on the user's system locale, use NumberFormat for robust, locale-friendly parsing:
val inputText = etProduktGekauftPreis.text.toString().trim() val numberFormat = NumberFormat.getInstance() numberFormat.isParseIntegerOnly = false // Ensure decimal values are allowed val preis = try { numberFormat.parse(inputText)?.toDouble() ?: 0.0 } catch (e: ParseException) { Toast.makeText(this, "Invalid number format", Toast.LENGTH_SHORT).show() 0.0 } val produkt = Produkt(name, anzahl.toInt(), preis)
3. Clean up input first
Always trim whitespace from the input string to eliminate hidden spaces that might break parsing:
val inputText = etProduktGekauftPreis.text.toString().trim()
内容的提问来源于stack exchange,提问作者Kevin

