How do I convert output of number_format back to numbers in PHP?

后端 未结 9 1480
星月不相逢
星月不相逢 2020-11-27 16:47

PHP can\'t recognize 1,200.00(generated by number_format) but only 1200.00,

What\'s the general solution for this problem?

相关标签:
9条回答
  • 2020-11-27 16:59

    You can use filter_var. e.g.

    $num = '1,200,998';
    $real_integer = filter_var($num, FILTER_SANITIZE_NUMBER_INT);
    echo $real_integer;
    

    will output:

    1200998
    
    0 讨论(0)
  • 2020-11-27 17:03

    In this case you can, use PHP round method like: round (12.000000, 2);

    0 讨论(0)
  • 2020-11-27 17:08

    You could do $num = (float) str_replace(',', '', $num); Basically, just get rid of the commas, and then cast it as a numeric type (float or int).

    0 讨论(0)
  • 2020-11-27 17:11

    I use the following code:

    function remove_non_numerics($str)
    { 
        $temp       = trim($str);
        $result  = "";
        $pattern    = '/[^0-9]*/';
        $result     = preg_replace($pattern, '', $temp);
    
        return $result;
    }
    
    0 讨论(0)
  • 2020-11-27 17:12

    The better way is to use the options in number_format function itself. The format is

    number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
    

    I.e. if you don't need the ',' in the formatted string make, it is like

    $num=23.33333
    echo number_format($num,2,'.','');
    

    If you need that as float then typecast the same to float

    $floatnum= (float) number_format($num,2,'.','');
    
    0 讨论(0)
  • 2020-11-27 17:13

    use "[^0-9.]+" regex.

    $formattedVal = '$9,99,999.99';
    $unformattedVal = (float)preg_replace("/[^0-9.]+/", "", $formattedVal);
    var_dump($unformattedVal);
    

    worked for me.

    0 讨论(0)
提交回复
热议问题