Dizzi
Dizzi

Reputation: 747

php abbreviating numbers with K/M

The function below finds the number, rounds it off and puts a K or M on the end of it

IE: 25000 becomes 25K

function abbr_no($number) {
 $number  = preg_replace('/[^0-9]/', '', $number);
 $numbers = array('', 'K', 'M');
if ($number == 0) { 
 return('n/a'); 
 } else {
 return (round($number/pow(10000, ($i = floor(log($number, 10000)))), 0) . $numbers[$i]);
 }
}

and so it basically does what I want, but as is for a number like 389345 it rounds it off and spits out 39K (as it should) however I would like the result to be 398K (3 digit number)

Now in the last return line:

0) . $numbers[$i]);

if I change the 0 to a 1 the result becomes 39.8K but again I don't want the decimal point so I am currently stuck and have hit a brickwall

As always all help is appreciated and thank you in advance.

Upvotes: 0

Views: 1051

Answers (2)

symcbean
symcbean

Reputation: 48357

This allows you to convert on all sorts of scales,

function humanize($val, $postfix)
{
    foreach ($postfix as $p=>$div) {
        $t=round($val/$div) . $p;
        if (strlen($t)<(3+strlen($p))) {
            break;
        }
    }
    return trim($t);
}

e.g.

$postfix=array(''=>1, 'K'=>1000,'M'=>1000000,'B'=>1000000000);

To answer the original question,

$postfix=array('walnut' => 0.16, 'chicken egg'=>0.35, 
    'grapefruit' => 1, 'bulgarian airbag' => 1.1,
    'bulgarian funbag'=>3.27, 'football' => 11.07, 
    'olympic swim pool' => 4780114, 'known universe'=>1.17456E4933);

for the Vulture Central Weights and Measures Soviet volume standard.

Upvotes: 1

Xitcod13
Xitcod13

Reputation: 6079

without editing much of your code you can add additional if statement test if the modular division by 1 yournumber%1

($i = floor(log($number, 10000)))), 0) % 1

gives you 0 if it doesnt then

multiply your number by 10 (you can make it a while statement so it multiplies it by 10 until there are no spaces after decimal point)

then return that number

so if you use your_number like 39.8 as an example it would look like this

while(your_number%1 != 0){
 your_number*=10;
}
return your_number;

This a quick fix but its definitely not the best way to code this

Upvotes: 0

Related Questions