您的位置:首页 > 其它

Intro:Formatting Numbers

2009-05-14 23:28 477 查看
When it comes to formatting numbers,PHP offers the number_format() function,which accepts four arguments:the number to formatted,the number of decimal places to display,the character to use instead of a decimal point,and the character to use to separate grouped thousands(usually a comma).Consider the following example,which illustrates:
--------------------------------------------------------------------------------
<?php
//format number(with defaults)
//output:1,106,483
$num=1106382.5843
echo number_format($num);
//format number(with custom separators)
//output:1?106?482*584
echo number_format($num,3,'*','?');
?>
For more control over number formatting,PHP offers the printf() and sprintf() functions.These functions,though very useful,can be intimidating to new users,and so the best way to understand them is with an example.Consider the next listing,whickh shows them in action:
---------------------------------------------------------------
<?php
//format as decimal number
//output:00065
printf("%05d",65);
//format as floating-point number
//output:00239.000
printf("%09.3f",239);
//format as octal number
//output:10
prinrf("%40",8);
//format number
//incorporate into string
print("I see %4d apples and %4.2f oranges",8,26);
?>
------------------------------------------------------------
Both functions accept two arguments,a series of format specifiers and the raw string or number to be formatted.The input is then formatted according to the format specifiers and the output either displayed with printf() or assigned to a variable with sprintf().
Some common format specifiers are listed below
specifier------what it means
%s             String
%d             decimal number
%x             hexadecimal number
%o             octal number
%f             floating-point number

You can also combine these format specifiers with a precision specifier,which indicates the number of digits to display for floating-point values-for example,%1.2f implies that the number should be formatted as a floating-point value with two digits displayed after the decimal point.For smaller numbers,it's also possible to add a padding specifier,which tells the function to pad the numbers to a specified length using a custom character.You can see both these types of specifiers in action in the preceding listing.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息