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 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计