我有一个关于php中变量类型的简单问题。我的数组中有两个值:
$row['DS'] // type :float (with one decimal like 12.2)
$row['TC'] // type :float (with one decimal like 24.2)我在下面的计算中实际尝试做的是:
$row['TC'] / $row['DS'] // $row['DS'] need to be as integer (without point,like 12)结果应该是两个小数,如(2.32)。我试着这样做
$DSF = number_format($row['DS'],0);
$ConF = $row['TC'] / $DSF ;
echo number_format($conF,2); 但是它返回了错误的结果。例如:
$row['DS'] = 59,009.3 ---> after change the format is change to 59,009
$row['TC'] = 190.0
$ConF = 190.0 / 59,009它应该是000.223 (大约在这个数字附近),我希望得到0(在我使用number_format($conF,2)改变格式后,但是程序返回给我的不是这个数字3.22.我做错了什么?
发布于 2012-08-02 19:57:19
函数number_format()用于将数字格式化为逗号样式的表示形式,而不是实际将数字舍入为您想要的数字。
您正在寻找的函数是round,它将浮点数返回到指定的小数位数。
例如:
$yourVar=round($row['TC']/$row['DS'],2);这意味着$yourVar将除法的值四舍五入到小数点后两位。
您应该只使用number_format()函数在末尾显示人类友好的数字。
发布于 2012-08-02 20:30:57
您可以在计算中使用type casting将$row['DS']转换为integer,例如:
$row['TC'] / (int)$row['DS']
或
$row['TC'] / intval($row['DS'])
https://stackoverflow.com/questions/11776802
复制相似问题