简体   繁体   中英

How to convert string operation into a number?

I have a '1/2' and i need to get a value 0.5 from it. '1/2' ,我需要从中获得一个0.5

Other examples: Operation: $operation = '5/8'; Wanted value: $value = 0.625;

You can use eval , also please note your are not looking for an int as they are whole numbers.

<?php

$operation = '1/2';

eval('$value = ' . $operation . ';');

echo $value;

?>

This will work if you only have one "/".

$str = '2/5';
$newStr = explode('/', $str);
echo $newStr[0]/$newStr[1];

Edited. Not elegant because eval is used, but working.

$operation = '1/2';

function stringCalc($operation){

    return eval('return '.$operation.';');
}

$value = stringCalc($operation);

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