Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active August 14, 2023 08:10
Show Gist options
  • Save code-boxx/398f55cc9b184c35e1df12ad6d3b16ea to your computer and use it in GitHub Desktop.
Save code-boxx/398f55cc9b184c35e1df12ad6d3b16ea to your computer and use it in GitHub Desktop.
PHP add comma to numbers

PHP ADD COMMA TO NUMBER

https://code-boxx.com/add-commas-number-php/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
// (A) THE NUMBER
$num = 12345.675;
// (B) ADD COMMAS
$formatted = number_format($num, 2);
echo $formatted; // 12,345.68
// (C) BLANK SPACES AS THOUSANDS SEPARATOR
$formatted = number_format($num, 3, ".", " ");
echo $formatted; // 12 345.675
// (D) ROUND BEFORE FORMATTING
$formatted = round($num, 2, PHP_ROUND_HALF_DOWN);
$formatted = number_format($formatted, 2);
echo $formatted; // 12,345.67
<?php
// (A) THE NUMBER
$num = 12345.78;
// (B) INSERT COMMAS
$pattern = "/\B(?=(\d{3})+(?!\d))/";
$replace = ",";
$commas = preg_replace($pattern, $replace, $num);
echo $commas; // 12,345.78
<?php
// (A) THE NUMBER
$num = 12345.678;
//$num = 1234567;
// (B) SPLIT WHOLE NUMBER & DECIMAL PLACES
$arrange = explode(".", $num);
// (C) ADD COMMAS
$arrange[0] = strrev($arrange[0]);
$arrange[0] = str_split($arrange[0], 3);
$arrange[0] = implode(",", $arrange[0]);
$arrange[0] = strrev($arrange[0]);
// (D) DEAL WITH DECIMALS - ROUND UP OR ROUND DOWN AS REQUIRED
if (isset($arrange[1])) {
$arrange[1] = "0.$arrange[1]";
$arrange[1] = (string)round($arrange[1], 2);
$arrange[1] = substr($arrange[1], 2);
}
// (E) COMBINE BACK
$num = isset($arrange[1])
? "$arrange[0].$arrange[1]"
: $arrange[0] ;
echo $num;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment