doulvli9462 2017-05-02 13:52
浏览 48
已采纳

浮点数的计算无法接近正确

I have a script that works out the instalments for a period of time again an amount.

Straight forward correct? well apparently not according to php.

Here is the posted form information, I know this is what is being posted because I am var_dump() all post values to make sure that is what is being posted.

array
    'total' => string string '999,999.99' (length=10)
    'howmany' => string '16,666.67' (length=9)
    'installmentcost1' => string '999,999.99' (length=10)

This is the very simple php formula

$tempInstallments = (intval($_POST['howmany'])) - 1; // get 1 less so we can make sure the last payment is within total amount
$tempInstallmentCost = (floatval($_POST['installmentcost1'])) * $tempInstallments; //installment price * the installment period minus 1 month
$tempTotal = floatval($_POST['cpototal']) - $tempInstallmentCost; // get the final payment cost

Now unfortunately this is for some reason giving me some really bad math which I am var_dump() out also.

Here is the var_dump I am using:

var_dump($tempInstallments);
var_dump($_POST['installmentcost1']);
var_dump($tempInstallmentCost);
var_dump($tempTotal);

Here is what is dumped out:

int 59
string '16,666.67' (length=9)
float 944
float 55

As you can see they are not even close to the actual information that is needed.

For instance it is meant to look like the following:

int 59
string '16,666.67' (length=9)
float 983,333.53 (length=10)
float 16,666.46 (length=9)

Any Ideas why this is happening. I am even making sure that the information is a definite float or int.

Thanks

  • 写回答

1条回答 默认 最新

  • du27271 2017-05-02 14:06
    关注

    intval() and floatval() don't handle punctuation, so intval("1,234.56") is 1. You can use filter_var() instead:

    $s = '1,234.56';
    var_dump(filter_var($s, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
    

    This yields:

    string(7) "1234.56"
    

    Which you can then intval() or floatval() if needed. Or just strip commas:

    $s = '1,234.56';
    $s = str_replace(',', '', $s);
    var_dump(floatval($s));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决