double number precision n decimal in kotlin
Table of Contents
- link
- Kotlin
1. kotlin.math.round
import kotlin.math.roundToInt
fun Double.roundTo(decimals: Int): Double {
var multiplier = 1.0
repeat(decimals) { multiplier *= 10 }
return (this * multiplier).roundToInt() / multiplier
}
2. String.format
import java.util.Locale
fun Number.roundTo(
numFractionDigits: Int
) = "%.${numFractionDigits}f".format(this, Locale.ENGLISH).toDouble()
3. BigDecimal
import java.math.RoundingMode fun Double.roundTo(decimals: Int) = this.toBigDecimal().setScale(decimals, RoundingMode.HALF_UP).toDouble()