Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 49 / 68

Formatting Numbers (Padding Digits, Decimal Places)

In this lesson you will learn to format numbers with format so amounts and sequential file names display neatly. This is for anyone searching for "Ruby format how to use".

format("%.2f", value) fixes the number of decimal places and 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 produces an amount with two decimal places using format("%.2f dollars", price), and a zero-padded three-digit sequence number with format("%03d", num). The format specifiers resemble C's printf syntax.

A common stumbling block for beginners is what the specifier characters mean. The f in %.2f is a floating-point number and the d in %03d is an integer - you pick them up gradually.

printf prints more directly and you pick to suit the job. 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 Ruby 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)