Formatting Numbers Easily

by Mar 5, 2014

Often, users need to format numbers and limit the number of digits, or add leading zeros. There is one simple and uniform strategy for this: the operator "-f"!

Let's make sure a number has leading zeros:

$number = 68

'{0:d7}' -f $number 

This will produce a 7-digit number with leading zeros. Adjust the number after "d" to control the number of digits.

To limit the number of digits, use "n" instead of "d". This time, the number after "n" controls the number of digits:

$number = 35553568.67826738

'{0:n1}' -f $number 

Likewise, use "p" to format percentages:

$number = 0.32562176536

'{0:p2}' -f $number 

Twitter This Tip! ReTweet this Tip!