Intro:Formatting Numbers

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值