How do we round only if the number is 10.0 Ex 10.0...
# mathematics
z
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
What output type do you want to have?
z
Double
Sorry String
a
Then maybe
num.toString().replace(".0", "")
❤️ 2
z
Oh yes this works!
Thank you
10.04 Cases in which this fails 🤔
104
i
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
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
Yes, regex solution will be correct but easier to make a mistake with.
4
i
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