doufu5747 2011-01-30 12:19
浏览 60
已采纳

添加数字不会产生预期的结果

I have 3 numbers returned from a database that I need to add together. For a total of 1,740.01, I get like 10.00. These are floating point numbers. Here are the actual numbers I'm having a problem with.

> 1,729.13
> 10.88
> 0.00

How do I get the correct total of these numbers?

EDIT

$cash = preg_replace('/\$/', '', $cash);
$card = preg_replace('/\$/', '', $card);
$check = preg_replace('/\$/', '', $check);

$cash = number_format(array_sum($cash), 2);
$card = number_format(array_sum($card), 2);
$check = number_format(array_sum($check), 2);
$total  = number_format( $cash + $card + $check, 2 );
  • 写回答

1条回答 默认 最新

  • doufei16736 2011-01-30 12:44
    关注

    Don't add values that have been formatted using number_format(), otherwise they may well contain , as a thousand's separator... they're treated as strings rather than floats.

    Assuming that $cash, $card and $check are arrays:

    $cash = array_sum($cash);
    $card = array_sum($card);
    $check = array_sum($check);
    
    $total  = number_format( $cash + $card + $check, 2 ); 
    
    $cash = number_format( $cash, 2 );
    $card = number_format( $card, 2 );
    $check = number_format( $check, 2 );
    

    Do any formatting after the math

    EDIT

    Use str_replace() rather than preg_replace() to strip out any $, then it's simple addition rather than needing to do the array_sum(), though I'm not sure where any $ is likely to come from if the values are DECIMAL 10,7 from the database

    $cash = (float) str_replace( array('$',','), '', $cash );
    $card = (float) str_replace( array('$',','), '', $card );
    $check = (float) str_replace( array('$',','), '', $check );
    
    $total  = number_format( $cash + $card + $check, 2 ); 
    
    $cash = number_format( $cash, 2 );
    $card = number_format( $card, 2 );
    $check = number_format( $check, 2 );
    

    (assumes that , is your thousands separator in the string values for $cash, $card and $check when doing the str_replace()

    EDIT 2

    To convert the $cash array to a sum of its values, having cleaned up any $ or , in the strings:

    $cash = array ( 0 => '$1729.13', 1 => '0.00', 2 => '$1,234.56' );
    
    function cleanArrayValues($value) {
        return (float) str_replace( array('$',','), '', $value );
    }
    
    $cash = array_sum(array_map('cleanArrayValues',$cash));
    

    I've added an extra value into the $cash array just to demonstrate.

    You'll need to filter $card and $checks in the same way, using the cleanArrayValues() callback function (if they're all arrays)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?