我如何考虑PHP钱的便士?

时间:2010-11-12 21:23:45

标签: php

好的,我有一个名为

的变量
$total_cost

等于529700

我需要价值为$ 5,297.00

此值来自mysql十进制10,2字段

我现在需要根据用户是否在州内提出2%的小计和8.25%的运费

让我们假设所有用户都来自这个状态,我将如何通过php来保存美分

例如,这就是我的想法

$subtotal = $total_cost * 0.02;
$shipping = $total_cost * 0.0825;
$new_total = $total_cost + $shipping + $subtotal;

但是当我打印出来时我得到0美元...任何想法

<?php print "$". $new_total; ?>

4 个答案:

答案 0 :(得分:2)

我在测试你的代码时没有得到那个结果......

php > $total_cost=529700;
php > $subtotal = $total_cost * 0.02;
php > $shipping = $total_cost * 0.0825;
php > $new_total = $total_cost + $shipping + $subtotal;
php > print "$". $new_total;
$583994.25

您确定初始值是您所期望的吗?

答案 1 :(得分:0)

你需要看看这个代码出现故障的地方,以及你认为你拥有的值实际上是在那里......这个输出是什么样的?

echo "Total: ".$total_cost."<br />";

$subtotal = $total_cost * 0.02;
echo "Sub: ".$subtotal . "<br />";

$shipping = $total_cost * 0.0825;
echo "Shipping: ".$shipping . "<br />";

$new_total = $total_cost + $shipping + $subtotal;
echo "New Total: ".$new_total . "<br />";

答案 2 :(得分:0)

This看起来可能对您有所帮助。抓取数字,除以100,进行计算并在输出过程中对其进行格式化。

<?php print "$".number_format($new_total/100, 2); ?>

请注意,您可以将数学组合成一个语句:

$new_total = $total_cost * 1.1025; // just add the numbers together and add 1

答案 3 :(得分:0)

计算百分比时,必须将其转换为浮点数,或者将整数向下舍入为0。

$subtotal = $totalcost / 100.0 * 0.02;
$shipping = $totalcost / 100.0 * 0.0825;
$newtotal = $totalcost / 100.0 + $subtotal + $shipping;