Format a double to fixed decimal length

Hi

I want to round a Double (12345.12345) to a String with a fixed length after the ‘.’

Example:

12345.123

And: if it is 12345.1
It still should give me

12345.100

How can I do this in kotlin?

2 Likes

Oh I got it:

String.format(“%.3f”, MyDecimalValue)

2 Likes

To forestall the next question: if you care about the exact decimals, you probably shouldn’t be using a binary floating-point type like Double.

(There’s no Double which has the exact value of 12345.12345 — just one with the nearest possible binary fraction to it. Functions like println() try to hide that by picking the most likely decimal number, but sooner or later you hit trouble.)

BigDecimal is often a good alternative.

2 Likes

The double type has 15 to 17 significant decimal digits precision. As long as you’re aware of that limitation, it’s not an issue.

Yes it is. decimal math can still introduce rounding errors even with only a few significant digits. When you really care about the exact result (eg. in regards to money) you should be using BigDecimal or some other system to ensure that the results are exact.

1 Like

Obviously the floating point data types are approximate. The original poster didn’t say anything about needing exact results.

Yup. It seems like OP was only concerned with formatting Doubles as Strings.

The other answers will definitely be helpful for others who find this thread in the future though.

1 Like