PHP

HOW TO ADD COMMAS TO NUMBERS IN PHP

(quick guide & examples)

NUMBER_FORMAT(NUMBER, DECIMAL PLACES, DECIMAL SEPARATOR, THOUSANDS SEPARATOR)

NUMBER FORMAT

01

NUMBER & DECIMAL PLACES - 1,234.68 $n = number_format(1234.678, 2);

DEFINE SEPARATORS - 1@234!68 $n = number_format(1234.678, 2, "!", "@"); 

THE NUMBER $n = 1234.678; 

REGULAR EXPRESSION

02

INSERT COMMA FOR EVERY 3 DIGITS (THOUSANDS) $pattern = "/\B(?=(\d{3})+(?!\d))/"; $n = preg_replace($pattern, ",", $n);

SPLIT WHOLE & DECIMAL NUMBERS  $n = explode(".", 1234.678);

MANUAL FORMAT

03

ADD COMMAS TO WHOLE $n[0] = strrev($n[0]); $n[0] = str_split($n[0], 3); $n[0] = implode(",", $n[0]); $n[0] = strrev($n[0]);

COMBINE BACK - 1,234.678 $n = "$n[0].$n[1]";