Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 49 / 68

Formatting Numbers (Padding Digits, Decimal Places)

In this lesson you will learn how to format numbers in Kotlin, lining up digits and decimal places so values display neatly. This is for anyone searching for "Kotlin String.format how to use".

String.format("%.2f", value) fixes the number of decimal places and String.format("%03d", value) pads the front of a number with zeros. Both are handy for displaying amounts or generating numbered file names.

The sample code turns 1234.5 into "1234.50 dollars" with two decimal places via String.format("%.2f dollars", price), and turns 7 into the zero-padded "007" via String.format("%03d", num).

A common stumbling block for beginners is the sheer number of format specifiers. There are %f for floats, %d for integers, %s for strings and many more, and you have to pick the one that fits.

In real-world development, raw calculation results have wildly varying widths, so applying this kind of formatting right before display is standard practice.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)