简体   繁体   English

从表单将字符串转换为整数

[英]Converting string to integer from form

Need a little help 需要一点帮助

I have 我有

$_POST["zapremina"]=2000;
$_POST["starost"]="15%";
$_POST["namena"]="50%";

I want simple function to do this 我想要简单的功能来做到这一点

$foo=(2000 - 15%) - 50%;

How to do that? 怎么做?

PHP is loosely typed, so you don't have to cast types explicity or do unnecessary operations (eg str_replace) PHP是松散类型的,因此您不必显式转换类型或进行不必要的操作(例如str_replace)

You can do the following: 您可以执行以下操作:

$z = $_POST["zapremina"]; //$_POST["zapremina"]=2000;
$s = $_POST["starost"];   //$_POST["starost"]=15%;
$n = $_POST["namena"];    //$_POST["namena"]="50%;

$result = (($z - ($z *($s / 100))) - ($z * ($n / 100)));

Remember to use parentheses to have a readable code and meaningful var names. 切记使用括号使代码可读并有意义的变量名。

Like this: 像这样:

$starostPercentage = (substr($POST["starost"], 0, -1) / 100);
$namenaPercentage = (substr($POST["namena"], 0, -1) / 100);

$foo = ($_POST["zapremina"] * (100 - $starostPercentage)) * $namenaPercentage;

This is what this does and why: 这就是这样做的原因:

  • Convert the percentages (like 15% ) from their text form to their decimal form ( substr(15%) = 15 , 15 / 100 = 0.15 ). 转换百分比(如15%从其文本形式)到他们的小数形式( substr(15%) = 1515 / 100 = 0.15 )。
  • Calculate $foo with these decimals. 用这些小数计算$foo 2000 - 15% is what you would write (as a human), but in PHP you need to write that as 2000 * (100 * 0.15) , meaning: 85% of 2000). 2000 - 15%是您要编写的(作为人类),但是在PHP中,您需要将其编写为2000 * (100 * 0.15) ,即:2000的85%。

I'd go with this: 我会这样:

  $zap = intval($_POST['zapremina']);
  $sta = intval($_POST['starost']);
  $nam = intval($_POST['namena']);
  $foo = ($zap * ((100-$sta)/100)) * ((100 - $nam)/100)

add this function and then call it 添加此函数,然后调用它

function calculation($a, $b, $c)
    {
        $b = substr($b, 0, -1) / 100;
        $c = substr($c, 0, -1) / 100;
        return (($a * $b) * $c);
    }

and now you can call 现在你可以打电话

$foo = calculation($_POST["zapremina"], $_POST["starost"], $_POST["namena"]);

go with function most of times, because it will be helpful for reusability. 大多数情况下都应该使用功能,因为这将有助于可重用性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM