I wanted to round a number in Kotlin/Multiplatform...
# random
r
I wanted to round a number in Kotlin/Multiplatform so I tried making a little function, but it didn't always work due to floating-point arithmetic and the existence of the digit 5. So after writing some tests and a more interesting algorithm, which still didn't work, I decided to use the collective knowledge of humanity and looked up how rounding is done. I found the seven ways the JVM can do it https://docs.oracle.com/javase/6/docs/api/java/math/RoundingMode.html I found the code that does it https://github.com/openjdk/jdk/blob/jdk-21-ga/src/java.base/share/classes/java/math/BigDecimal.java#L2842 I'm now reconsidering life choices. I just wanted to round a number. I also understand why it's not in the stdlib yet.
😁 3
s
Out of curiosity, why round a number in multiplatform code? I'm oversimplifying, but I think my rule of thumb would be to round numbers only at the system boundary, and only when rendering them as text
r
Yes, you should probably rely on an existing platform implementation on all platforms where you want to display numbers using
expect
/
actual
. In my case I'm in common Compose code and I just wanted to make a quick function to round numbers for display. It can't be that hard, right? 🤡
👍 1
s
I spent some time working on a product which had to calculate and display currency values. I remember for a while there was a whole team just working on number rounding. They ultimately claimed they had come up with a better algorithm than the ones in Java… I was never quite convinced 🤔
😆 1
There must be somebody working on a decimal number library for Kotlin, it seems like the kind of thing people would need
p
Not sure about your specific concern but usually in finance you either work with Big decimal which I think has a KMP lib somewhere or you just don't use decimal points. Treat all your numbers as long and shift 2 places the coma at the end of your computations. You won't risk any rounding presicion error, or decimal number representation in binary error
2
e
Not sure about your specific concern but usually in finance you either work with Big decimal which I think has a KMP lib somewhere or you just don’t use decimal points.
+1. Worked on a big finance project and we used BigDecimal wrapped inside a value class for some added niceties and had zero issues with rounding/precision.
👍 2
d
I commonised
BigDecimal
and
NSDecimalNumber
for a financial product. Unfortunately I can't make the code available, but it was successful despite not being as trivial as you might hope! Nice thing was I ended up with a battery of many Unit Tests in common code that asserted the same results from both platforms across many types of rounding and arithmetic operations to prove it. I also used value class as @edrd did.
❤️ 1