Weight in words

6 Jan

I’m sharing a simple piece of PHP code I’ve wrote that returns a given weight in words.

My function uses the SI (International System of Units), but you can easily change the code and adapt it to another measurement system. It’s also simple translate it to another programming language.

function weight($weight) {
  $weight = (float) $weight;
  $int = intval($weight);
  $dec = $weight - $int;
  $text = '';
  if ($int > 0) {
    $text .= $int . ' ' . ($int > 1 ? 'kilos' : 'kilo');
  }
  if ($dec > 0) {
    if ($int > 0) {
      $text .= ' e ';
    }
    $dec = round($dec * 1000);
    $text .= $dec . ' ' . ($dec > 1 ? 'grams' : 'gram');
  }
  return $text;
}

Usage:

echo weight(20.2307);
echo weight(1);
echo weight(3);
echo weight(1.001);
Advertisement

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.