Skip to content

Instantly share code, notes, and snippets.

@bastman
Last active July 27, 2021 07:06
Show Gist options
  • Save bastman/bc9f86e5e3abf0cc1328783476108832 to your computer and use it in GitHub Desktop.
Save bastman/bc9f86e5e3abf0cc1328783476108832 to your computer and use it in GitHub Desktop.
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