【问题标题】:Divide a $1 by 3 and adjusting 1 cent将 1 美元除以 3 并调整 1 美分
【发布时间】:2015-04-26 19:59:37
【问题描述】:

我有一个存储在购物车表中的价格,并试图找到一种方法在价格除以 3 或任何其他奇数时调整 1 美分。

$cost = '1';
$split  = '3';

$check1 = $cost/$split; // .33
$check2 = $cost/$split; // .33
$check3 = $cost/$split; // this should give .34

如何调整差异?

【问题讨论】:

  • What have you tried? 我的第一个虽然只是在做$check3 = $cost - $check1 - $check2;
  • 您将拆分设置为变量,这表明它将发生变化。在此基础上,为什么要创建 $check1$check2 等变量。如果 split 为 4,则没有第四个检查变量。

标签: php


【解决方案1】:

好的,如果你想拥有无限的$checks 并且只有最后一个 $check 包含其余部分,你可以这样做:

<?php
    $cost=1;
    $split=3;
    $q=round($cost/$split,2);
    $r=$cost-($split*$q);

    $firstchecks=$q;
    $lastcheck=$q+$r;
?>

【讨论】:

    【解决方案2】:

    类似

    $cost = 1;
    $split = 3;
    $check1 = $cost/split;
    $total = intval($check1*100)*($split-1);
    $diff = $cost - $total/100;
    

    【讨论】:

      【解决方案3】:

      为什么不四舍五入到小数点后第二位:

      function roundUp ($v,$d = 2 ) { 
           $p=pow(10,$d); 
           $c=ceil($p*$v);
           return ($c+ceil($p*$v-$c))/$p; 
      } 
      
      echo roundUp(1/3); // 0.34
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-31
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 2011-01-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多