PHP:Convert a Number to a String

From Progzoo
Jump to: navigation, search

There is usually no need to convert between numbers and strings in PHP. Numbers and strings are interchangeable: if you use a number in a place that expects a string (e.g. the concatenation operator "."), it will automatically be converted into a string; conversely, if you use a string in a place that expects a number (e.g. arithmetic operators), it will automatically be converted into a number.

The easy way to do this is to interpolate it in a double-quoted string

You can also use the strval function

The powerful way to do this is to use the sprintf function

Number to String by interpolation

[Font] [Default] [Show] [Resize] [History] [Profile]

Number to String by strval

[Font] [Default] [Show] [Resize] [History] [Profile]

Creating a string

The sprintf function takes a format string and a list of arguments. The format string includes %d spaces where the integers should go or %f places for the floating point numbers.

We can specify the total number of characters to use (the number is right justified in this space). We can specify the number of decimal places to use.

[Font] [Default] [Show] [Resize] [History] [Profile]