0

我有一个关于 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 我做错了什么?

4

2 回答 2

1

该函数number_format()用于将数字格式化为逗号样式表示,而不是实际将数字四舍五入为您想要的。

您正在寻找的函数是round,它将浮点数返回到指定的小数位数。

例如:

$yourVar=round($row['TC']/$row['DS'],2);

这意味着$yourVar将四舍五入到小数点后两位的除法值。

您应该number_format()只使用该功能在最后显示人性化的数字。

于 2012-08-02T11:57:19.303 回答
0

您可以在计算中使用右type casting转换$row['DS']integer例如:

$row['TC'] / (int)$row['DS']

或者

$row['TC'] / intval($row['DS'])

于 2012-08-02T12:30:56.630 回答