how to reformat a number with commas

前端 未结 4 1257
忘掉有多难
忘掉有多难 2020-12-20 02:36

I have a line of code that get a count of rows in my table and then display the count. In this case it display the number of downloads.

Right now the count is very s

4条回答
  •  無奈伤痛
    2020-12-20 02:58

    If somebody is looking for the reverse of PHP's number_format function (by the title of this question), here is one:

    /**
     * @param string $string
     * @param int $decimals
     * @param string $dec_point
     * @param string $thousands_sep
     *
     * @throws InvalidArgumentException
     * @return float
     */
    function number_from_format($string, $decimals = 0, $dec_point = '.', $thousands_sep = ',') {
        $buffer = $string = (string) $string;
        $buffer = strtr($buffer, array($thousands_sep => '', $dec_point => '.'));
        $float = (float) $buffer;
        $test = number_format($float, $decimals, $dec_point, $thousands_sep);
        if ($test !== $string) {
            throw new InvalidArgumentException(sprintf('Unable to parse float from "%s" as number "%s".', $string, $test));
        }
        return $float;
    }
    

    Usage Example:

    var_dump(number_from_format('1,200.00', 2)); # double(1200)
    

提交回复
热议问题