溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP如何自帶函數(shù)給數(shù)字或字符串自動(dòng)補(bǔ)齊位數(shù)

發(fā)布時(shí)間:2021-07-02 15:47:25 來(lái)源:億速云 閱讀:333 作者:chen 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要講解了“PHP如何自帶函數(shù)給數(shù)字或字符串自動(dòng)補(bǔ)齊位數(shù)”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“PHP如何自帶函數(shù)給數(shù)字或字符串自動(dòng)補(bǔ)齊位數(shù)”吧!

先來(lái)看個(gè)例子:需求為生成4位數(shù),不足前面補(bǔ)0

<?php  
//生成4位數(shù),不足前面補(bǔ)0  
$var=sprintf("%04d", 2);
echo $var;//結(jié)果為0002  
echo date('Y_m_d', time()).'_'.sprintf('d', rand(0,99));
?>

sprintf()函數(shù)

有沒(méi)有感覺(jué)很像c語(yǔ)言

1. 語(yǔ)法

sprintf(format,arg1,arg2,arg++)
參數(shù) 描述
format 必需。轉(zhuǎn)換格式。
arg1 必需。規(guī)定插到 format 字符串中第一個(gè) % 符號(hào)處的參數(shù)。
arg2 可選。規(guī)定插到 format 字符串中第二個(gè) % 符號(hào)處的參數(shù)。
arg++ 可選。規(guī)定插到 format 字符串中第三、四等等 % 符號(hào)處的參數(shù)。

2. 說(shuō)明

參數(shù) format 是轉(zhuǎn)換的格式,以百分比符號(hào) ("%") 開(kāi)始到轉(zhuǎn)換字符結(jié)束。下面的可能的 format 值:

%% - 返回百分比符號(hào)
%b - 二進(jìn)制數(shù)
%c - 依照 ASCII 值的字符
%d - 帶符號(hào)十進(jìn)制數(shù)
%e - 可續(xù)計(jì)數(shù)法(比如 1.5e+3)
%u - 無(wú)符號(hào)十進(jìn)制數(shù)
%f - 浮點(diǎn)數(shù)(local settings aware)
%F - 浮點(diǎn)數(shù)(not local settings aware)
%o - 八進(jìn)制數(shù)
%s - 字符串
%x - 十六進(jìn)制數(shù)(小寫(xiě)字母)
%X - 十六進(jìn)制數(shù)(大寫(xiě)字母)
arg1, arg2, ++ 等參數(shù)將插入到主字符串中的百分號(hào) (%) 符號(hào)處。該函數(shù)是逐步執(zhí)行的。在第一個(gè) % 符號(hào)中,插入 arg1,在第二個(gè) % 符號(hào)處,插入 arg2,依此類推。

<?php  
$number = 123;  
$txt = sprintf("%f",$number);  
echo $txt;  
?>

3. 格式數(shù)字 number_format()

<?php  
$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>

感謝各位的閱讀,以上就是“PHP如何自帶函數(shù)給數(shù)字或字符串自動(dòng)補(bǔ)齊位數(shù)”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)PHP如何自帶函數(shù)給數(shù)字或字符串自動(dòng)補(bǔ)齊位數(shù)這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI