1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

How do I convert this string to float number?

Discussion in 'PHP' started by JEET, Aug 24, 2020.

  1. #1
    How do I convert this string to float number?

    <?php
    $s="1/2";
    echo (0+($s)); //echos 1
    echo floatval($s); //echos 1
    ?>

    How do I convert it to 0.5 in PHP?
    Thanks
     
    JEET, Aug 24, 2020 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,494
    Likes Received:
    4,457
    Best Answers:
    123
    Trophy Points:
    665
    #2
    I'm sure you can tidy this up a lot, but it works
    function handleAddition($str){
        $nums = [];
        $bits = explode('+',$str);
        //print_r($bits);
        foreach($bits as $bit){
            $nums[] = handleSubtraction($bit);
        }
        //print_r($nums);
        $result = $nums[0];
        for($i = 1; $i < count($nums); $i++){
            $result += $nums[$i];
        }
        return $result;
    }
    
    function handleSubtraction($str){
        $nums = [];
        $bits = explode('-',$str);
        //print_r($bits);
        foreach($bits as $bit){
            $nums[] = handleMultiplication($bit);
        }
        //print_r($nums);
        $result = $nums[0];
        for($i = 1; $i < count($nums); $i++){
            $result -= $nums[$i];
        }
        return $result;
    }
    function handleMultiplication($str){
        $nums = [];
        $bits = explode('*',$str);
        //print_r($bits);
        foreach($bits as $bit){
            $nums[] = handleDivision($bit);
        }
        //print_r($nums);
        $result = $nums[0];
        for($i = 1; $i < count($nums); $i++){
            $result = $result * $nums[$i];
        }
        return $result;
    }
    function handleDivision($str){
        $nums = [];
        $bits = explode('/',$str);
        //print_r($bits);
        foreach($bits as $bit){
            $nums[] = intval($bit);
        }
        //print_r($nums);
        $result = $nums[0];
        for($i = 1; $i < count($nums); $i++){
            $result = $result / $nums[$i];
        }
        return $result;
    }
    
    
    $s="1/2";
    
    echo handleAddition("1+2");
    echo '<hr>';
    echo handleAddition("5-2");
    echo '<hr>';
    echo handleAddition("3*2");
    echo '<hr>';
    echo handleAddition("6/2");
    PHP:
     
    sarahk, Aug 24, 2020 IP
    JEET likes this.
  3. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #3
    Thanks @sarahk

    I was hoping there might be some function like eval etc that could do the trick.

    Will use your solution. Thanks! :)
     
    JEET, Aug 25, 2020 IP
  4. SpacePhoenix

    SpacePhoenix Well-Known Member

    Messages:
    196
    Likes Received:
    28
    Best Answers:
    2
    Trophy Points:
    155
    #4
    Assuming that with 1/2 both being variables, why not type cast them as floats upstream of that bit of code?
     
    SpacePhoenix, Aug 25, 2020 IP
    JEET likes this.
  5. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #5
    @SpacePhoenix
    typecasting also did not worked.
    $s is storing data from form, like someone enters a math formula, and my PHP executes it.
    I tried:
    $s="1/2";
    echo (float)$s; // still gives 1, not 0.5
    ?>


    This one below is working, but I do not want to use this because its data taken from form...

    <?php
    $s="1/2";
    $v='';
    $s= '$v= ('.$s.');';
    eval( $s );
    echo $v;
    //gives 0.5
    ?>
     
    JEET, Aug 25, 2020 IP
  6. sarahk

    sarahk iTamer Staff

    Messages:
    28,494
    Likes Received:
    4,457
    Best Answers:
    123
    Trophy Points:
    665
    #6
    run a regex over it to reject if there are any characters that aren't digits or your math symbols?
     
    sarahk, Aug 25, 2020 IP
    JEET likes this.
  7. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #7
    @sarahk
    What will be regex to allow these symbols "()^%+/*.-%d%s"
    I am not at all good with regex...
    I want to allow all those symbols inside quote marks including space and numbers, and remove everything else.
    Thanks
     
    JEET, Aug 25, 2020 IP
  8. sarahk

    sarahk iTamer Staff

    Messages:
    28,494
    Likes Received:
    4,457
    Best Answers:
    123
    Trophy Points:
    665
    #8
    I'm a copy and paster when it comes to regex but google should be helpful.
     
    sarahk, Aug 25, 2020 IP
  9. BUMROG

    BUMROG Greenhorn

    Messages:
    9
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    8
    #9
    /^[0-9\(\)\^\%\+\/\*\.\-\" ]*$/
    Code (markup):
    Dirty, but should work. Long story short, do the usual regex and escape any special characters that need to be kept.
     
    BUMROG, Aug 25, 2020 IP
    JEET likes this.
  10. JEET

    JEET Notable Member

    Messages:
    3,825
    Likes Received:
    502
    Best Answers:
    19
    Trophy Points:
    265
    #10
    @BUMROG
    Thanks, this worked!
    $s="?php 1/2 echo 'this'; ";
    $s= preg_replace( '/[^0-9\(\)\^\%\+\/\*\.\- ]*/', '', $s );
    echo $s; // gives 1/2 only

    Thanks!
     
    JEET, Aug 26, 2020 IP
  11. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #11
    NetStar, Sep 6, 2020 IP
    sarahk likes this.
  12. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #12
    Assuming one's hosting allows you to install PEAR stuff, which many do not... Which sucks... which is why you don't find PEAR in a lot of mainstream codebases.

    It also lacks string input, so one would also still have to split it to make the numerator and denominator, since it accepts either float as a single parameter, or numerator/denominators as separate integers. At which point by the time you trim and typecast, and the result desired is float, you might as well just:

    
    function strFractionToFloat($str) {
    	[ $numerator, $denominator ] = explode('/', $str, 2);
    	return intval(trim($numerator)) / intval(trim($denominator));
    }
    
    Code (markup):
    Which would be a lot easier than:

    
    function strFractionToFloat($str) {
    	[ $numerator, $denominator ] = explode('/', $str, 2);
    	$fraction = Math_Fraction(intval(trim($numerator)), intval(trim($denominator));
    	return $fraction.toFloat();
    }
    
    Code (markup):
    This isn't rocket science and certainly doesn't warrant a regex, much less the security risks of an eval. No need to get a bigass class from an optional library involved when all that's needed is a simple divide.

    **NOTE** I used PHP 7.1+ destructuring. If you "need" earlier PHP replace

    [ $numerator, $denominator ]

    with

    list($numerator, $denominator)
     
    Last edited: Sep 7, 2020
    deathshadow, Sep 7, 2020 IP
    JEET likes this.