0

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?

Benjamin H
  • 5,164
  • 6
  • 34
  • 42

2 Answers2

1

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

Seems class extension function will help:

fun Double.str(decPlaces: Int): String = "%.${decPlaces}f".format(this)

and use it like

LOG.info { "It went ${distance.str(3)}" }
Slava Glushenkov
  • 1,378
  • 1
  • 9
  • 10