Banner of

1K, 1.234M Human readable formatted numbers in PHP, Python, C and C++


Category: Programming

Date: October 2022
Views: 815


1K, 1.25M Human Readable, formatted numbers in PHP, Python, C and C++

We take the value of our number and we keep dividing it by 1000, each time we increase the magnitude by 1. we consider the number as powers of 1000

1,000 a magnitude of 1 -> k

1,000,000 a magnitude of 2 -> M and so forth

and finaly we print the number divided by the 1000 to the power of the magnitude, think of it as a scientifc format of the number

Python

    
def human_format(value):
    if value<1000:
	return value
    num = value
    magnitude = 0
    while abs(num) >= 1000:
	magnitude += 1
	num /= 1000.0
    result = round(value / (1000**magnitude),3)
    return f"{result}{' KMBT'[magnitude]}"
    

PHP

    
function human_format($n, $point='.', $sep=',') {
	if ($n < 0) {
	    return 0;
	}
	if ($n < 10000) {
	    return number_format($n, 0, $point, $sep);
	}
	$d = $n < 1000000 ? 1000 : 1000000;
	$f = round($n / $d, 1);
	return number_format($f, $f - intval($f) ? 1 : 0, $point, $sep) . ($d == 1000 ? 'k' : 'M');
}
    

C

    
// compile with gcc -lm
#include <stdio.h>
#include <math.h>

const char symbols[] = {' ','K','M','T'};
void human_format(int n, char* human_number){
    int magnitude = 0 ,tmp = n;
    while (tmp > 1000){
	 magnitude++;
	 tmp /= 1000;
    }
    sprintf(human_number,"%.3f%c", (double) n / pow(1000.0,magnitude),symbols[magnitude]);
}

int main() {
    char n[7];
    human_format(1234,n);
    printf("%s",n); // 1.234K
    return 0;
}
    

C++

    
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
#include <iomanip>

const char symbols[] = {' ','K','M','T'};
std::string human_number(int n){
    int magnitude = 0;
    double tmp = n;
    std::ostringstream ss;
    while ( tmp > 1000 ){
        magnitude++;
        tmp /= 1000;
    }
    ss  << std::fixed
        << std::setprecision(3)
        << n / pow(1000.0,magnitude)
        << symbols[magnitude];
    return ss.str();
}
int main() {
    std::cout<< human_number(1234);
    return 0;
}
    



815 views

Next Article

0 Comments, latest

No comments.