ana*_*abi 8 string floating-point type-conversion representation kotlin
大多数答案使用 Java(例如String.format)来完成工作,但我需要一种方法来完全使用 Kotlin 原生来支持多平台编程。
这意味着不使用 Java 包
说一个像 fun Float.toString(numOfDec: Int) 这样的方法。我希望该值四舍五入,例如:
35.229938f.toString(1) 应该回来 35.2
35.899991f.toString(2) 应该回来 35.90
小智 5
如果您想返回浮点数,但仅删除尾随小数,请使用以下命令:
fun Float.roundToDecimals(decimals: Int): Float {
var dotAt = 1
repeat(decimals) { dotAt *= 10 }
val roundedValue = (this * dotAt).roundToInt()
return (roundedValue / dotAt) + (roundedValue % dotAt).toFloat() / dotAt
}
Run Code Online (Sandbox Code Playgroud)
我创建了以下 Float 扩展(这也应该适用于 Double):
/**
* Return the float receiver as a string display with numOfDec after the decimal (rounded)
* (e.g. 35.72 with numOfDec = 1 will be 35.7, 35.78 with numOfDec = 2 will be 35.80)
*
* @param numOfDec number of decimal places to show (receiver is rounded to that number)
* @return the String representation of the receiver up to numOfDec decimal places
*/
fun Float.toString(numOfDec: Int): String {
val integerDigits = this.toInt()
val floatDigits = ((this - integerDigits) * 10f.pow(numOfDec)).roundToInt()
return "${integerDigits}.${floatDigits}"
}
Run Code Online (Sandbox Code Playgroud)