本文目錄一覽:
用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中,如何獲取小數點後面的數字
使用字元串截取函數explode,因為PHP是弱類型語言,所以可以直接使用
?
$x=98.6;
$y=explode(“.”,$x);
echo $y[0].”——“;//98
echo $y[1]; //6
?
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
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/201171.html