本文目錄一覽:
請教,php保留兩位小數,但不四捨五入
使用bc一類的函數,按字符串方式運算即可。
/**
* 數值非四捨五入保留兩位小數
* @author Zjmainstay
* @website
* @param $num 數值
* @return 保留兩位小數
*/
function getNum($num, $scale = 2) {
$numStr = (string)$num . str_repeat(‘0’, $scale);
//匹配精度前的數值
if(preg_match(‘#^\d+\.\d{0,’.$scale.’}#’, $numStr, $match)) {
return $match[0];
} else {
return ‘0’;
}
}
echo getNum(10.0253) . “\n”;
echo getNum(0.5) . “\n”;
PHP怎麼定義保留2位小數的變量
在php中要保留兩位小數的方法有很多種辦法,有如:printf,substr,number_format,round等等方法
方法一
sprintf()函數 ,sprintf() 函數把格式化的字符串寫寫入一個變量中
?php
$number = 123;
$txt = sprintf(“%f”,$number);
echo $txt;
?
輸出:
123.000000
方法二 substr()函數
$num = 123213.666666;
echo sprintf(“%.2f”,substr(sprintf(“%.3f”, $num), 0, -2));
方法三 number_format()函數
$number = 1234.5678;
$nombre_format_francais = number_format($number, 2, ‘,’, ‘ ‘); // 1234,57
$english_format_number = number_format($number, 2, ‘.’, ”); // 1234.57(我一般用這個)
方法四 round 函數,round() 函數對浮點數進行四捨五入。
?php
echo(round(0.60));
echo(round(0.50));
echo(round(0.49));
echo(round(-4.40));
echo(round(-4.60));
?
輸出:
1
1
-4
-5
如果要保留小數,後來參數根保留小數位數即可。
$number = 1234.5678;
echo round($number ,2); //1234.57
用php使數字保留小數點後兩位怎麼做的?
PHP 中的 round() 函數可以實現
round() 函數對浮點數進行四捨五入。
round(x,prec)
參數說明
x 可選。規定要舍入的數字。
prec 可選。規定小數點後的位數。
返回將 x 根據指定精度 prec (十進制小數點後數字的數目)進行四捨五入的結果。prec 也可以是負數或零(默認值)。
注釋:PHP 默認不能正確處理類似 “12,300.2” 的字符串。
例如:
?php
echo round(-4.635,2);
?
輸出: -4.64
PHP如何保留2位小數
要分2種情況。
1、數值不變,只在輸出時保留2位小數。
echo sprintf(‘%.2f’, 3.1415);
2、數值上保留2位
echo round(3.1415, 2);
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/279336.html