https://kotlinlang.org logo
z

zain

10/26/2021, 10:11 AM
How do we round only if the number is 10.0 Ex 10.0 = 10 10.3 = 10.3 10.7 = 10. 7 Is there any easier way
a

altavir

10/26/2021, 11:07 AM
What output type do you want to have?
z

zain

10/26/2021, 11:15 AM
Double
Sorry String
a

altavir

10/26/2021, 11:19 AM
Then maybe
num.toString().replace(".0", "")
❤️ 2
z

zain

10/26/2021, 11:27 AM
Oh yes this works!
Thank you
10.04 Cases in which this fails 🤔
104
i

Iaroslav Postovalov

10/26/2021, 11:43 AM
The most correct solution for Kotlin/JVM is:
Copy code
private val MY_FORMAT = DecimalFormat("0.#")
...
val price = 4.3000
println(MY_FORMAT.format(price)) // 4.3
👍 2
a

altavir

10/26/2021, 11:45 AM
Then you have to use regular expression that ensures that this zero is the last. What @Iaroslav Postovalov is simpler of course, but it works more or less the same inside.
i

Iaroslav Postovalov

10/26/2021, 11:47 AM
Yes, regex solution will be correct but easier to make a mistake with.
4
i

Ilmir Usmanov [JB]

10/27/2021, 2:20 AM
Well, stringifying doubles "correctly", which means, choosing least significant bit(s) in a way, that string representation will be the shortest, in short, is not easy, yet straightforward and can be explained with a bit of math. The simplest I found is in EcmaScript 'Number::toString' section, and it is still couple pages long. There is also a paper https://ampl.com/REFS/rounding.pdf and https://netlib.sandia.gov/fp/dtoa.c, which the standard mentions.
🤔 1
5 Views