PHP number_format是否舍入? [英] PHP number_format is rounding?

查看:129
本文介绍了PHP number_format是否舍入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的价格为"0,10"或"00000,10"

I have a price "0,10" or "00000,10"

现在当我尝试

number_format($price, 2, ',', '')

我得到0,00. 我怎样才能解决这个问题?我要0.10美元. 我不要四舍五入.

I get 0,00. How can i fix this? I want 0,10 $. I don't want rounding.

或者当我有5,678时,我得到5,68.但我要5,67.

Or when i have 5,678, i get 5,68. But i want 5,67.

推荐答案

几个人提到将其舍入为3,然后删除最后一个字符.这实际上是行不通的.假设您有2.9999,并将其四舍五入为3.000.

Several people have mentioned rounding it to 3 and then dropping the last character. This actually does not work. Say you have 2.9999 and round it to 3 it's 3.000.

这仍然不准确,最佳解决方案是:

This is still not accurate, the best solution is this:

$price = '5.678';
$dec = 2;
$price = number_format(floor($price*pow(10,$dec))/pow(10,$dec),$dec);

这是将价格乘以100(10十进制)得出567.8,然后使用下限将其乘以567,然后将其除以100得到5.67

What this does is takes the price and multiplies it by 100 (10^decimal) which gives 567.8, then we use floor to get it to 567, and then we divide it back by 100 to get 5.67

这篇关于PHP number_format是否舍入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆