Skip to content

Instantly share code, notes, and snippets.

@gcphost
Last active October 26, 2021 08:40
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gcphost/589d915e2c2f67270cc9bdade732b77f to your computer and use it in GitHub Desktop.
Save gcphost/589d915e2c2f67270cc9bdade732b77f to your computer and use it in GitHub Desktop.
Pretty PHP Numbers, convert a number to K, M, B, etc.
<?php
function human_number($number) {
$number = preg_replace('/[^\d]+/', '', $number);
if (!is_numeric($number)) {
return 0;
}
if ($number < 1000) {
return $number;
}
$unit = intval(log($number, 1000));
$units = ['', 'K', 'M', 'B', 'T', 'Q'];
if (array_key_exists($unit, $units)) {
return sprintf('%s%s', rtrim(number_format($number / pow(1000, $unit), 1), '.0'), $units[$unit]);
}
return $number;
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'human_number'
})
export class HumanNumberPipe implements PipeTransform {
constructor() { }
transform(value: number) {
if (!value) {
return 0
}
if (value < 1000) {
return value
}
let unit = Math.floor(Math.log(value) / Math.log(1000)),
units = { 0: '', 1: 'K', 2: 'M', 3: 'B', 4: 'T', 5: 'Q' };
if (unit in units) {
return (Math.round((value / Math.pow(1000, unit)) * 10) / 10) + units[unit]
}
return 0
}
}
@gcphost
Copy link
Author

gcphost commented Aug 17, 2016

Convert numbers to a pretty format using PHP or Angular 2 Typescript Pipe.

  • 200 = 200
  • 2,000 = 2K
  • 2,100 = 2.1K
  • 20,000 = 20K
  • 20,100 = 20.1K
  • etc

@SirDagen
Copy link

Greetings. After I uploaded my code to Github and googled for "pretty numbers php" I saw that we created something similar ( https://github.com/SirDagen/php-beautiful-numbers ). Nice to know. - btw I love your compact code

@fre2mansur
Copy link

fre2mansur commented Apr 26, 2020

Is there a way to do reverse? If i enter numbers with k or m it should convert to full number?

@vrajroham
Copy link

It does not work for all numbers.

Try these edge cases,

human_number(100000); //Returns 1K
human_number(20000); //Returns 2K

@vrajroham
Copy link

vrajroham commented Oct 26, 2021

Here is the simpler version,

// Constants
// 1E9 = 1000000000
// 1E6 = 1000000
// 1E3 = 1000

function human_number($number)
  {
    if ($number >= 1E9) {
        return round($number / 1E9, 2).'b';
    } else if ($number >= 1E6) {
        return round($number / 1E6, 2).'m';
    } else if ($number >= 1E3) {
        return round($number / 1E3, 2).'k';
    }
    return $number;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment