Kotlin中百分比计算的正确语法咨询(含错误代码分析)
Ah, I get it—your original code isn't giving the right result because of integer division in Kotlin! Let me break down what's happening and show you the correct way to handle this.
The Problem with Your Original Code
When you write (count/totalCount) * 100 where both count and totalCount are integers, Kotlin performs integer division. That means it discards any decimal part of the result entirely. For example:
- If
count = 7andtotalCount = 20,7/20becomes0(not0.35), so multiplying by 100 gives0instead of the expected35.
Correct Implementations
To fix this, you need to convert at least one of the integers to a floating-point type (like Double or Float) before doing the division. Here are a few clean, practical ways to do it:
Basic Accurate Calculation
// Convert count to Double first to force floating-point division val percentage = (count.toDouble() / totalCount) * 100 it.toast("Percentage: $percentage")
Formatting for Clean Display (e.g., 2 Decimal Places)
If you want to show the percentage neatly with a fixed number of decimal places, use String.format:
val percentage = (count.toDouble() / totalCount) * 100 // This will output something like "Percentage: 35.00%" it.toast("Percentage: %.2f%%".format(percentage))
Safely Handle Division by Zero
Don’t forget to account for cases where totalCount might be 0 (to avoid a runtime error):
val percentage = if (totalCount == 0) { 0.0 // Adjust this fallback value to fit your app's logic } else { (count.toDouble() / totalCount) * 100 } it.toast("Percentage: %.2f%%".format(percentage))
Key Takeaway
The core issue was integer division—by converting one operand to a floating-point type, you ensure the division retains the decimal value, leading to an accurate percentage calculation.
内容的提问来源于stack exchange,提问作者Abdul Mateen

