Skip to content
Advertisement

PHP Convert any kg amount to a readable metric unit

I am trying to create a mathematical function (in PHP) that will take a given number of Kg, and convert them to a readable form or better yet, return the unit best suited for that amount. The input will always be kg. Preferably log.

For example:

5 kg = (5) kg

0.5 kg = (500) gm

1000 kg = (1) tonne

0.001 kg = (1) gm

0.0001 kg = (100) mg

I know there is a way to do it using log or log10 functions but I cannot figure it out.

How could it be done?

Advertisement

Answer

After playing with it for a while, here is what I came up with

    function readableMetric($kg)
    {
        $amt = $kg * pow(1000, 3);
        $s = array('mcg', 'mg', 'gm', 'kg','tonne');
        $e = floor(log10($amt)/log10(1000));
        return [
            "amount" => $amt/pow(1000, $e),
            "unit"   => $s[$e]
        ];
    }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement