简体   繁体   中英

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)

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 ).
  • Calculate $foo with these decimals. 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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