Two methods of PHP digital complement

Source: Internet
Author: User

There are two functions in PHP--at least two are there any other I do not know, can achieve the number of 0, Str_pad (), sprintf () details as follows

Str_pad

As the name implies, this function is for a string that can fill any other string with the specified string.

For example: Str_pad (with a filled string, filling the length, filling the string, filling the position)

The length of the fill must be a positive integer, the fill position has three options,

Left: Str_pad_left,

Right: Str_pad_right,

Ends: Str_pad_both

For example:

Echo Str_pad (1, 8, "0″,str_pad_left");

Results: 00000001

Echo Str_pad (1, 8, "0″,str_pad_right");

Results: 10000000

Echo Str_pad (1, 8, "0″,str_pad_both");

Results: 00010000

One of the notable details in the above example is that if the number of digits filled is odd, such as example three fills 7 0, the right priority.

Another way to see Zero is sprintf

This function learned C is very familiar with it, hehe ...

But I do not say so much, because it is too flexible to use, so that I basically do not use, but on the left 0 (or 0 after the decimal point) is very convenient to use.

First look at the left 0

Echo sprintf ("%05d", 1);

First say the meaning of%05d, with a 5-digit number to format the parameters behind, if less than 5 0

Operation result is 00005

Look at the decimal point after 0

Echo sprintf ("%01.3f", 1);

%01.3f means that a minimum of three digits after a decimal point is less than three 0, at least one digit before the decimal point, and a floating-point number that is less than a zero complement is formatted with the parameters behind it.

The operation result is: 1.000

About the two methods of zero complement you can choose to use, in fact, each has the pros and cons, sprintf can ensure that you do not mistakenly operate it 1 1000000 haha, Str_pad can guarantee you want to fill what.

Two methods of PHP digital complement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.