Olaf Gottschalk
02/10/2025, 4:02 PMNumber.toBigDecimal()
? I struggle with this a lot as there are specific functions Int.toBigDecimal()
and so on, even for the real tricky cases like Double.toBigDecimal()
which does the "right" thing using the String constructor of BigDecimal
rather than the double constructor which may lead to real spooky results...
So in my code, I write my own extension function:
fun Number.toBigDecimal(): BigDecimal = when(this) {
is Short -> this.toBigDecimal()
is Int -> this.toBigDecimal()
.......
}
This is highly repetitive and error prone... so, why is this function just missing from the standard lib?Youssef Shoaib [MOD]
02/10/2025, 4:08 PMNumber
and define their own type. There is no standard way to take an arbitrary user-defined Number
class and find a BigDecimal
that corresponds to it.Olaf Gottschalk
02/10/2025, 4:12 PMtoDouble()
, toInt()
functions defined inside Number
and thought: where's toBigDecimal()
- but I guess the answer to that simply is that BigDecimal
is not a "platform class representing a number" as the KDoc states... I just use it so often cause it's on the JVM but maybe not on all platforms? If it were on all platforms, I would simply rephrase my question why this function is missing in the abstract Number class...Olaf Gottschalk
02/10/2025, 4:13 PMYoussef Shoaib [MOD]
02/10/2025, 4:16 PMtoBigDecimal()
as a required function in kotlin.Number
would be conceivably possible (with a deprecation cycle and some warnings and such, and ofc a KMP BigDecimal
type). The real issue is that java.lang.Number
doesn't have such a method, and so there's java implementers of Number
that we can do nothing about (note that kotlin.Number
maps to java.lang.Number
and vice versa)Olaf Gottschalk
02/10/2025, 4:19 PMYoussef Shoaib [MOD]
02/10/2025, 4:28 PMNumber
is really badly designed anyways. It has no plus
or other operators. It doesn't really have much sensible use. What would've been better is some interfaces like Addable
, Multipliable
, but that ship has sailed. With context parameters though, we can make something somewhat useful: https://github.com/kotlin-graphics/imgui/blob/master/core/src/main/kotlin/imgui/genericMath.kt. You could make something similar to convert numbers into BigDecimal
easily, or, y'know, just stick with the extension methodKlitos Kyriacou
02/10/2025, 4:32 PMBigDecimal literally is the only type that can cover all in terms of the contained valueNot really. There are, for example rational numbers (with several third-party implementations out there). A
BigDecimal
cannot represent Rational(1, 3)
. On the other hand, rationals would be the only number type that could represent anything currently available in the stdlib (but not third-party libs).