Home  >  Article  >  Backend Development  >  Two ways to implement digital zero padding in PHP

Two ways to implement digital zero padding in PHP

不言
不言Original
2018-09-11 14:48:342276browse

The content of this article is about two methods of implementing digital zero padding in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There are two functions in php - at least two of them. I don’t know if there are others, which can realize digital zero padding. The details of str_pad() and sprintf() are as follows

str_pad
As the name suggests, this function is for strings. It can fill the specified string with any other string

For example: str_pad (string with padding, after padding length, padding string, padding position)

The padded length must be a positive integer, there are three options for padding position,
Left side: STR_PAD_LEFT,
Right side: STR_PAD_RIGHT,
Both End: STR_PAD_BOTH

For example:

echo str_pad(1,8,”0″,STR_PAD_LEFT);

Result: 00000001

echo str_pad(1,8,”0″,STR_PAD_RIGHT);

Result: 10000000

echo str_pad(1,8,”0″,STR_PAD_BOTH);

Result: 00010000

One detail worth noting in the above example is that if the number of digits to be filled is an odd number, for example, 7 0s are filled in in Example 3, the right side is given priority.

Let’s look at another method of zero padding, sprintf

Everyone who has studied C knows this function very well, haha...

But we won’t say so much, because It’s so flexible to use that I basically don’t use it, but it’s still very convenient to pad zeros on the left (or pad zeros after the decimal point)

Look at padding zeros on the left first
echo sprintf ("d",1);
Let’s talk about the meaning of d first. Use a 5-digit number to format the following parameters. If there are less than 5 digits, add zeros.

The running result is 00005

Look at the padding of zeros after the decimal point

echo sprintf(”%01.3f”,1);

.3f means that after a decimal point, use at least three digits and less than three digits to pad zeros, and before the decimal point, use at least one digit and less than one digit to pad zeros. The parameters after formatting the floating point number

The running result is: 1.000

Related recommendations:

Introduction to two functions of PHP to implement the digital zero padding function

php number zero padding format

The above is the detailed content of Two ways to implement digital zero padding in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn