Search code examples
kotlinkotlin-extension

Possible to Kotlin extend/override Double.toString to produce less decimal places?


I already have a hack:

/** Shorter round for the logs */
val Double.str: String
    get() = "%.3f".format(this)

But that has to be manually inserted into all of my LOG.info { "It went ${distance.str}" } statements. I'd prefer to be able to set the (float and decimal) significant digits globally. Is there any way to make this happen?


Solution

  • No, there's no way to do so. Instead, you could redefine your LOG methods, but they'll likely need to take parts as separate parameters (i.e. LOG.info("It went {}", distance) or LOG.info { myformat("It went {}", distance) }). You'd need to decide if that's a trade-off you want.

    The only way I can see for LOG.info { "It went ${distance}" } to work is to find numbers in the interpolated string using regular expressions and replace them. Which is a pretty ugly hack and relatively slow.