z

    zain

    10 months ago
    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
    altavir

    altavir

    10 months ago
    What output type do you want to have?
    z

    zain

    10 months ago
    Double
    Sorry String
    altavir

    altavir

    10 months ago
    Then maybe
    num.toString().replace(".0", "")
    z

    zain

    10 months ago
    Oh yes this works!
    Thank you
    10.04 Cases in which this fails 🤔
    104
    i

    Iaroslav Postovalov

    10 months ago
    The most correct solution for Kotlin/JVM is:
    private val MY_FORMAT = DecimalFormat("0.#")
    ...
    val price = 4.3000
    println(MY_FORMAT.format(price)) // 4.3
    altavir

    altavir

    10 months ago
    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 months ago
    Yes, regex solution will be correct but easier to make a mistake with.
    i

    Ilmir Usmanov [JB]

    10 months ago
    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.