Ho can I divide unsigned types with numeric places...
# android
l
Ho can I divide unsigned types with numeric places?
Copy code
val value: UInt = 137
println("Value: ${value / 10F}") // Does not work
I can't find any hint how to the division. The result should be 13.7
e
on JVM you can
Copy code
value.toLong().toBigDecimal().scaleByPowerOfTen(-1)
but there is no kotlin-stdlib functionality
that being said, the full range of UInt is exactly representable as Double, so
value.toDouble() / 10.0
should format to more-or-less the same
l
Copy code
value.toDouble() / 10.0
Good point, thanks!
c
Although you'll lose precision, as always with float operations (so if it's important that the number is exact, don't use that)
e
(UInt.MAX_VALUE.toDouble() / 10.0).ulp ≈ 2.9802322387695312E-8
(2^-25) so there is definitely enough precision for one decimal point
so yes, you do need to be careful with floating point precision in general, but in this particular case, it is enough for printing
although you will run into the challenge that
429496729.5.toString()
will be in scientific notation by default (on JVM), and there's no platform-independent way to control numeric formatting in Kotlin