本文目錄一覽:
請教,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位小數
今天處理數據的時候因為要保留2位小數,查看幫助手冊
?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 保留小數點後2位
兩種取值法,看你需要什麼結果:
1 四捨五入(簡單,自帶函數就可以解決)
$youWantNum = sprintf(‘%.2f’, $num);
//有人說用floor,floor是取整的函數,無法直接取小數;但可以轉換得到結果,那就是下面的例子
2 捨去後面的,不管是什麼
/*
*$num 要處理的浮點數
*$digits 保留的小數位數
* 實現思路:先乘以10的小數位數次方,用floor向下取整,再除以除數得到捨去後面位數的結果
* 最後再用sprintf配合位數再取一次值(此處是為了解決有些數字,最後一位為零時不顯示問題)
*/
function floorFloat($num, $digits) {
$num = floatval($num);
$multiple = pow(10, $digits);
$tempNum = floor($num*$multiple);
return sprintf(‘%.’.$digits.’f’, $tempNum/$multiple);
}
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
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/197038.html