Home > Backend Development > PHP Tutorial > php 如何用去尾法保留两位小数

php 如何用去尾法保留两位小数

WBOY
Release: 2016-06-06 20:12:05
Original
2627 people have browsed it

需求是财务那边提出的,我现在用的是这个
sprintf("%.2f", substr(sprintf("%.4f", $profits), 0, -2));
但是像是 19.9997 要变成19.99就做不到了。

回复内容:

需求是财务那边提出的,我现在用的是这个
sprintf("%.2f", substr(sprintf("%.4f", $profits), 0, -2));
但是像是 19.9997 要变成19.99就做不到了。

JS中不就是这样做的吗?

$a= 19.9997;

echo floor($a*100)/100;

<code class="php">$pos = stripos(19.9997,'.');
echo substr(19.9997,0,$pos+3);</code>
Copy after login

可以借助bcmath函数来处理

bcmul(19.9997, 1, 2)

可以考虑正则表达式

<code>$arr = array();
$preg = 19.9997;
$mattch = "/\w+.\w{2}/";
$result = preg_match($mattch,$preg,$arr);
echo "<pre class="brush:php;toolbar:false">";
print_r($arr);
echo $result;
Copy after login

number_format

格式化成保留3位小数再去掉最后一个数字便是

使用number_format函数最为直接, $english_format_number = number_format($number, 2, '.', '');
// 1234.57

详细用法访问php.net官网。

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template