Last active
July 27, 2021 07:06
-
-
Save bastman/bc9f86e5e3abf0cc1328783476108832 to your computer and use it in GitHub Desktop.
fun Double.round(decimals:Int)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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