diff --git a/CHANGELOG.md b/CHANGELOG.md index 19e95aed9f7..d23d1cf5cfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## 0.17.3 * `Common`: + * Add `fixed` extensions for `Float` and `Double` * New function `emptyDiff` * Now you may pass custom `comparisonFun` to all `diff` functions diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/ToFixed.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/ToFixed.kt new file mode 100644 index 00000000000..61797b470e2 --- /dev/null +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/ToFixed.kt @@ -0,0 +1,6 @@ +package dev.inmo.micro_utils.common + +val FixedSignsRange = 0 .. 100 + +expect fun Float.fixed(signs: Int): Float +expect fun Double.fixed(signs: Int): Double diff --git a/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/toFixed.kt b/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/toFixed.kt new file mode 100644 index 00000000000..44a6d18fd34 --- /dev/null +++ b/common/src/jsMain/kotlin/dev/inmo/micro_utils/common/toFixed.kt @@ -0,0 +1,4 @@ +package dev.inmo.micro_utils.common + +actual fun Float.fixed(signs: Int): Float = this.asDynamic().toFixed(signs.coerceIn(FixedSignsRange)).unsafeCast().toFloat() +actual fun Double.fixed(signs: Int): Double = this.asDynamic().toFixed(signs.coerceIn(FixedSignsRange)).unsafeCast().toDouble() diff --git a/common/src/jvmMain/kotlin/dev/inmo/micro_utils/common/ToFixedActual.kt b/common/src/jvmMain/kotlin/dev/inmo/micro_utils/common/ToFixedActual.kt new file mode 100644 index 00000000000..9ef32711fce --- /dev/null +++ b/common/src/jvmMain/kotlin/dev/inmo/micro_utils/common/ToFixedActual.kt @@ -0,0 +1,12 @@ +package dev.inmo.micro_utils.common + +import java.math.BigDecimal +import java.math.RoundingMode + +actual fun Float.fixed(signs: Int): Float = BigDecimal.valueOf(this.toDouble()) + .setScale(signs.coerceIn(FixedSignsRange), RoundingMode.HALF_UP) + .toFloat(); + +actual fun Double.fixed(signs: Int): Double = BigDecimal.valueOf(this) + .setScale(signs.coerceIn(FixedSignsRange), RoundingMode.HALF_UP) + .toDouble();