ian
ian

Reputation: 12335

how to reformat a number with commas

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 small but when it gets larger ( great than 1000) I would like to format it to display with commas in the correct spots example:

1,000

100,000

1,000,000

Or perhaps with a . 1.000 1.000.000

What is the simplest way to do this?

Upvotes: 2

Views: 2437

Answers (4)

hakre
hakre

Reputation: 197682

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)

Upvotes: 1

Anax
Anax

Reputation: 9372

You can also use FORMAT(X, D) in your query:

Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part.

mysql> SELECT FORMAT(12332.123456, 4);

    -> '12,332.1235'

mysql> SELECT FORMAT(12332.1,4);

    -> '12,332.1000'

mysql> SELECT FORMAT(12332.2,0);

    -> '12,332'

Edit:

I was about to add that "the downside of using this method is that you cannot that number in your code", but apparently this is not a problem anymore, starting from PHP 5.3, thanks to the parse function of NumberFormatter class:

NumberFormatter::parse numfmt_parse

— Parse a number

Example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."\n";
echo $fmt->parse($num, NumberFormatter::TYPE_INT32)."\n";
?>

Upvotes: 5

LiraNuna
LiraNuna

Reputation: 67252

I believe you are looking for the PHP built-in number_format.

Upvotes: 2

Greg
Greg

Reputation: 321598

You can use the number_format() function:

$str = number_format($number);

To use "." instead of ",":

$str = number_format($number, 0, ',', '.');

Upvotes: 16

Related Questions