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

后端 未结 9 1481
星月不相逢
星月不相逢 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 17:16

    If you're using 5.3 or higher (thanks ircmaxell), use numfmt_parse.

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

    You could remove any character that is not a digit or a decimal point and parse that with floatval:

    $number = 1200.00;
    $parsed = floatval(preg_replace('/[^\d.]/', '', number_format($number)));
    var_dump($number === $parsed);  // bool(true)
    

    And if the number has not . as decimal point:

    function parse_number($number, $dec_point=null) {
        if (empty($dec_point)) {
            $locale = localeconv();
            $dec_point = $locale['decimal_point'];
        }
        return floatval(str_replace($dec_point, '.', preg_replace('/[^\d'.preg_quote($dec_point).']/', '', $number)));
    }
    
    0 讨论(0)
  • 2020-11-27 17:18

    use ; Sanitize filters

    $number1= '$ 1,989.34';

        $number2 = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);//1989.34
        $number2 = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);//1,98934
    
    0 讨论(0)
提交回复
热议问题