PHP - Add commas to number

From Global Programming Syntax

Jump to: navigation, search

Sometimes you may want to add commas to a number so instead of a number displaying as 10000 it would display as 10,000. This can be usefull if you are dealing with huge numbers that are unreadable without the commas and can be achieved with a simple php function which will convert your number to a string containing the commas. The function is as follows:

<?php
function addcommas($v) {
$arr=str_split($v);
$k=count($arr);
foreach ($arr AS $val) {
$k--;
$arr[$k]=$val;
}
$arr=implode('',$arr);
$arr=str_split($arr,3);
$arr=implode(',',$arr);
$arr.=',';
$arr=str_split($arr,4);
$k=count($arr);
foreach ($arr AS $val) {
$k--;
$arr[$k]=$val;
}
$value=implode('',$arr);
return substr($value,0,-1);
}
//now to use it
echo addcommas(12345678900987654321);
//above displays: 12,345,678,900,987,654,321
?>
Personal tools
languages
page stats
Toolbox