PHP:修改价格看起来很漂亮?

Ind*_*ial 0 php math function

我们都看到商店的产品定价很好; "1.99","209.90"等.

如果你手动输入价格,这也很容易做到,但是我们说我们会有一个存储价格的数据库,每天根据货币变化进行更新.因此,价格会自动计算出来并最终看起来像"1547,83",这对眼睛来说并不好看.

如何在PHP中创建一个函数,既可以根据奖金的大小对价格进行舍入并根据设置的公差将其调整为"可呈现"?

非常感谢!

Mar*_*ker 6

money_format()number_format() 后者通常更好 - 尽管名称 - 为货币值

编辑

根据Pekka的评论,number_format()和round()的组合可能会提供您想要的内容:

$value = 1547.83;

echo number_format($value,2),'<br />';
echo number_format(round($value,1),2),'<br />';
echo number_format(round($value,0),2),'<br />';
echo number_format(round($value,0)-0.01,2),'<br />';
echo number_format(round($value,-1),2),'<br />';
Run Code Online (Sandbox Code Playgroud)

1,547.83
1,547.80
1,548.00
1,547.99
1,550.00
Run Code Online (Sandbox Code Playgroud)

编辑2

略微更加模糊,根据实际值确定舍入级别:

$value = 1547.83;
$pos = 3 - floor(log10($value));
echo number_format(round($value,$pos)-0.01,2),'<br />';

//  gives 1,547.99

$value = 1547982.83;
$pos = 3 - floor(log10($value));
echo number_format(round($value,$pos)-0.01,2),'<br />';

//  gives 1,547,999.99
Run Code Online (Sandbox Code Playgroud)