Mike Barwick Mike Barwick - 4 months ago 13
PHP Question

Abbreviate Number Function Won't Output Negative Value

So I have this class, which appreciates numbers. For example,

AbbreviateNum::convert(1178);
will round up and turn it into
1.18K
.

This works as it should, nicely. However, I can't seem to figure out how to output negative numbers. If I run
AbbreviateNum::convert(-1178);
, it will output the same response
1.18K
. Without the negative indicator.

Any tips on how I fix this?

<?php

namespace App\Helpers;

class AbbreviateNum
{

/**
* Abbreviate long numbers
*
* @return Response
*/
public static function convert($num)
{
$num = preg_replace('/[^0-9]/', '', $num);
$sizes = array("", "K", "M");

if ($num == 0) return(0);
else return (round($num/pow(1000, ($i = floor(log($num, 1000)))), 2) . $sizes[$i]);
}

}

Answer

Here is the modified function that provides a little bit more robustness for the strings it will accept.

public static function convert($num)
{
    $num = intval(preg_replace('/[^\-\.0-9]/', '', $num));
    $sizes = array("", "K", "M");

    if ($num == 0) return(0); 
    else return (round($num/pow(1000, ($i = floor(log(abs($num), 1000)))), 2) . $sizes[abs($i)]);
}