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: accessibility