ionspin / kotlin-multiplatform-bignum

A Kotlin multiplatform library for arbitrary precision arithmetics
Apache License 2.0
339 stars 40 forks source link

Create BigDecimal via 10.dec or 10.9.dec or "10".dec #272

Closed CodeServant closed 5 months ago

CodeServant commented 7 months ago

Is your feature request related to a problem? Please describe. Since BigDecimal is just a number, I think this is a bit inconvenient to call every time 10.toBigDecimal() when I want to treat number as BigDecimal.

Describe the solution you'd like Change (hide) BigDecimal creation behind something like n.dec where n is some number. This is very simple to implement with extension value

val Int.dec: BigDecimal
get(){
    return this.toBigDecimal()
}

Describe alternatives you've considered Alternative is the status quo or different naming. There is extension function Int.dec() for decrementing values, but dec alone could do the work.

Similar solution is used in Jetpack Compose.
What do you think about this enhancement? Maby this will be too confusing?

ionspin commented 7 months ago

I think it's an interesting idea, dec might be a bit to confusing because, like you said theres already dec() for decrementing values that is well known. There is additional consideration, the signature of toBigDecimal let's say for double is this:

/**
 * Converts a number to big decimal, optionally modifies the exponent and provides decimal mode.
 * Example:
 *      1234.0.toBigDecimal() produces 1.234E3
 *      1234.0.toBigDecimal(exponentModifier = 2) produces 1.234E5 (original exponent was 3 and modifier adds 2)
 */
fun Double.toBigDecimal(exponentModifier: Long? = null, decimalMode: DecimalMode? = null): BigDecimal {
    return BigDecimal.fromDouble(this, decimalMode).moveDecimalPoint(exponentModifier ?: 0)
}

the approach with extension property would miss this abilty to set decimalMode and modify exponent.

I guess this could become a discussion?

CodeServant commented 7 months ago

I didn't take that into account. So if, to implement it, this shoud be still extension function, but with shorter name. Maby this is not a good idea.