JavaScript and PHP Function To Shorten Long Numbers To K, M, B
When working with large numbers in JavaScript or PHP, displaying them in a readable format is crucial, especially for dashboards, statistics, and financial data. A common approach is to shorten numbers by converting thousands to "K", millions to "M", and billions to "B".
This article provides both JavaScript and PHP functions to format numbers dynamically based on their size. Additionally, you can try our Online Number Shortener Tool to instantly convert large numbers into a compact format without writing any code.
Online Number Shortener Tool
- 1,000 → 1K (Thousand)
- 1,000,000 → 1M (Million)
- 1,000,000,000 → 1B (Billion)
- 1,000,000,000,000 → 1T (Trillion)
- 1,000,000,000,000,000 → 1P (Quadrillion)
- 1,000,000,000,000,000,000 → 1E (Quintillion)
Enter a number in the textbox below and click the "Convert" button to see the shortened result in K, M, or B format.
JavaScript Function Number Convert
Converts a number to a readable string with K, M, B, T, P, E
const formatNumber = (num, decimals = 2) => {
if (num == null) return 'Invalid input';
// Convert input to a number, removing non-numeric characters if it's a string
let numValue = typeof num === 'string' ? parseFloat(num.replace(/[^0-9.-]/g, '')) : Number(num);
if (isNaN(numValue)) return 'Invalid input';
// Determine if the number is negative and get its absolute value
const isNegative = numValue < 0;
const absValue = Math.abs(numValue);
// If the absolute value is below 1000, return it as is
if (absValue < 1000) return isNegative ? `-${absValue}` : absValue;
// Define suffixes for large numbers
const suffixes = [
{ value: 1e18, symbol: 'E' },
{ value: 1e15, symbol: 'P' },
{ value: 1e12, symbol: 'T' },
{ value: 1e9, symbol: 'B' },
{ value: 1e6, symbol: 'M' },
{ value: 1e3, symbol: 'K' }
];
// Find the largest suffix that fits the number
const suffix = suffixes.find(({ value }) => absValue >= value);
if (!suffix) return numValue.toString();
// Format the number by dividing by the suffix value and fixing decimals
let formattedValue = (absValue / suffix.value).toFixed(decimals);
// Remove trailing zeros and unnecessary decimal points
formattedValue = formattedValue.replace(/\.?0+$/, '');
// Add back the negative sign if needed and append the suffix
return (isNegative ? '-' : '') + formattedValue + suffix.symbol;
};
usage:
// Example Usage:
// Large numbers
console.log(formatNumber(12345678)); // "12.35M"
console.log(formatNumber("12345678")); // "12.35M"
// Negative number
console.log(formatNumber("-12345678")); // "-12.35M"
// Small numbers (less than 1000)
console.log(formatNumber(1000)); // "1K"
console.log(formatNumber(999)); // "999"
// Decimal handling
console.log(formatNumber("12345678.90")); // "12.35M"
console.log(formatNumber("12345678", 1)); // "12.3M"
console.log(formatNumber(12345678, 1)); // "12.3M"
// String with numbers inside
console.log(formatNumber("abc12345678def")); // "12.35M"
// Invalid input cases
console.log(formatNumber("invalid")); // "Invalid input"
console.log(formatNumber(null)); // "Invalid input"
console.log(formatNumber(undefined)); // "Invalid input"
PHP Function Thousand Format
How to format numbers in PHP. Below PHP function code for Thousands number format to 1K. Convert large number into short K, M, B, T, P, E
<?php
function formatNumber($num, $decimals = 2) {
// Return '0' if input is null or undefined
if ($num === null) return '0';
// Convert input to a numeric value
$numValue = is_string($num) ? floatval(preg_replace('/[^0-9.\-]/', '', $num)) : floatval($num);
// Return '0' if conversion results in NaN
if (!is_numeric($numValue)) return '0';
// Determine if the number is negative and get its absolute value
$isNegative = $numValue < 0;
$absValue = abs($numValue);
// If the absolute value is below 1000, return it as is
if ($absValue < 1000) return strval($numValue);
// Define suffixes for large numbers
$suffixes = [
1e18 => 'E', // Exa
1e15 => 'P', // Peta
1e12 => 'T', // Tera
1e9 => 'B', // Billion
1e6 => 'M', // Million
1e3 => 'K' // Thousand
];
// Find the largest suffix that fits the number
foreach ($suffixes as $value => $symbol) {
if ($absValue >= $value) {
// Format number and remove trailing zeros
$formattedValue = number_format($absValue / $value, $decimals, '.', '');
$formattedValue = rtrim(rtrim($formattedValue, '0'), '.');
// Return formatted number with suffix and sign
return ($isNegative ? '-' : '') . $formattedValue . $symbol;
}
}
return strval($numValue);
}
usage:
<?php
// Example Usage:
echo formatNumber(12345678) . "\n"; // "12.35M"
echo formatNumber("12345678") . "\n"; // "12.35M"
// Negative number
echo formatNumber("-12345678") . "\n"; // "-12.35M"
// Small numbers (less than 1000)
echo formatNumber(1000) . "\n"; // "1000"
echo formatNumber(999) . "\n"; // "999"
// Decimal handling
echo formatNumber("12345678.90") . "\n"; // "12.35M"
echo formatNumber("12345678", 1) . "\n"; // "12.3M"
echo formatNumber(12345678, 1) . "\n"; // "12.3M"
// String with numbers inside
echo formatNumber("abc12345678def") . "\n"; // "12.35M"
Features
Function Features of formatNumber
Handles Various Input Types
- Accepts numbers and numeric strings (e.g.,
12345678
or"12345678"
). - Parses numeric values from strings with mixed characters (e.g., "
abc12345678def"
→"12.35M"
). - Handles negative numbers properly (e.g.,
-12345678
→"-12.35M"
).
Number Formatting & Scaling
- Formats large numbers using K (thousands), M (millions), B (billions), T (trillions), P (quadrillions), E (quintillions)
- Keeps small numbers (below 1000) unchanged (e.g.,
999
→"999"
). - Removes unnecessary trailing zeros (e.g.,
12.00M
→"12M"
).
Customizable Decimal Places
- Supports a decimal precision parameter (e.g.,
formatNumber(12345678, 1)
→"12.3M"
). - Defaults to two decimal places if not specified.
Error Handling
- Returns
"Invalid input"
for non-numeric values (e.g.,"invalid"
,null
,undefined
). - Prevents
NaN
issues from invalid number conversions.
Simple JavaScript and PHP Function Number Convert
Here is the simple light weight PHP and JavaScript functions number convert to a readable string with K, M, B, T, P, E.
JavaScript Code Snippet:
function shortenNumber(num) {
if (num >= 1_000_000_000) {
return (num / 1_000_000_000).toFixed(1).replace(/\.0$/, '') + 'B';
} else if (num >= 1_000_000) {
return (num / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
} else if (num >= 1_000) {
return (num / 1_000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return num.toString();
}
// Example Usage
console.log(shortenNumber(1200)); // "1.2K"
console.log(shortenNumber(1500000)); // "1.5M"
console.log(shortenNumber(2500000000)); // "2.5B"
PHP Code Snippet:
<?php
function shortenNumber($num) {
if ($num >= 1000000000) {
return number_format($num / 1000000000, 1, '.', '') . 'B';
} elseif ($num >= 1000000) {
return number_format($num / 1000000, 1, '.', '') . 'M';
} elseif ($num >= 1000) {
return number_format($num / 1000, 1, '.', '') . 'K';
}
return (string) $num;
}
// Example Usage
echo shortenNumber(1200); // "1.2K"
echo shortenNumber(1500000); // "1.5M"
echo shortenNumber(2500000000); // "2.5B"