sprintf in PHP differs from printf function usage

Source: Internet
Author: User
Tags mixed sprintf string format

Here's an example: rounding to keep the two digits after the decimal point

The code is as follows Copy Code

<?php
$num 1 = 21;
Echo sprintf ("%0.2f", $num 1). " <br/> "; Output 21.00
$num 2 = 16.3287;
Echo sprintf ("%0.2f", $num 2). " <br/> "; Output 16.33
$num 3 = 32.12329;
Echo sprintf ("%0.2f", $num 3). " <br/> "; Output 32.12 Www.111Cn.net
?>

Explain the meaning of the%0.2f:

% indicates starting character
0 means the vacancy is filled with 0.
2 indicates that two digits must be taken after the decimal point
f indicates conversion to floating-point number


Convert character
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
% print percent symbol, do not convert.
The b integer is converted into binary.
The c integer is converted to the corresponding ASCII character.
The d integer is turned into 10.
The F times the precision number is converted to floating point numbers.
The o integer is converted into octal.
The s integer turns into a string.
The x integer is converted to lowercase 16.
The X integer is converted to uppercase 16.

The difference between printf and sprintf

1. printf function:

int printf (string format [, mixed args [, mixed ...]])

Produces output according to format, which are described in the documentation for SPRINTF ().

Returns the length of the outputted string.

Format the text after the output, such as:

The code is as follows Copy Code
$name = "Hunte";
$age = 25;
printf ("My name was%s, age%d", $name, $age);

2. sprintf function:
String sprintf (string format [, mixed args [, mixed ...]])

Returns a string produced according to the formatting string format.

Similar to printf, but does not print, but returns the formatted text, the rest is the same as printf.


3. Print function:

is a function that can return a value and can have only one argument.

int print (string arg)

Outputs Arg. Returns 1, always.

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.