Skip to content

Instantly share code, notes, and snippets.

@bastman
Last active Jul 27, 2021
Embed
What would you like to do?
fun Double.round(decimals:Int)
// see discussion on alternatives here: https://discuss.kotlinlang.org/t/how-do-you-round-a-number-to-n-decimal-places/8843/15
fun Double.round(decimals:Int, roundingMode:RoundingMode=RoundingMode.HALF_EVEN):Double =
toBigDecimal().setScale(decimals, roundingMode).toDouble()
# ???
fun Double.round2(decimals: Int): Double {
val locale:Locale = Locale.US
val aTxt:String = String.format(locale, "%.${decimals+1}f", this)
val aDouble:Double = aTxt.toDouble()
val bTxt:String = String.format(locale, "%.${decimals}f", aDouble)
return bTxt.toDouble();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment