Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 49 / 68

Formatting numbers (aligning digits and decimal places)

This lesson covers formatting numbers in R, with the aim of displaying them in a readable form.

sprintf("%.2f", value) fixes the number of decimal places, and sprintf("%03d", value) pads the front with zeros to a fixed width. Both are handy for displaying amounts and for building numbered file names.

The sample code turns 1234.5 into two-decimal form with sprintf("%.2f dollars\n", price) and 7 into the zero-padded "007" with sprintf("%03d\n", num). Note the difference between the %f and %d specifiers.

A common early stumble is the sheer number of format specifiers. Knowing a handful of these format strings lets you meet most display requirements quickly.

In professional work, formatting numbers is essential to presenting analysis clearly, as in statistical report output.

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

๐Ÿงช This site can't compile or run R 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)