F
F
forwox2021-08-06 23:42:39
PHP
forwox, 2021-08-06 23:42:39

How to decompose a mass written in kg into all units of measurement?

Good day!

There is a table like this:
610d9b09e612f700571902.png
The base unit of measurement in it is the kilogram.
There is a formula

$quantity = 12514.1212134545342; // КГ
$units = массив с данными из таблицы.
function fullNameUnit($quantity,$units) {
          $res = array(); 
          foreach ($units as $unit) {   
              if ($quantity==0) { break; }
              $res[$unit['code']] = rtrim(floor($quantity / $unit['base_unit_quantity'])); 
              $quantity = $quantity % $unit['base_unit_quantity'];
          }
          return $res;
}
dd($quantity . ' кг', fullNameUnit($quantity,$data);

The result of the function execution
610d9b8b77fb9459991797.png
The function, by break, stops at kg and does not count what is after the decimal point in the $quantity variable, because otherwise an error occurs. But it is necessary that the weight be displayed in full, for example like this:
11 tons 7 centners 34 kilograms 120 grams 210 centigrams 454 milligrams 534 micrograms

How to fix this? How can this feature be improved?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
galaxy, 2021-08-07
@galaxy

// $quantity = $quantity % $unit['base_unit_quantity'];
$quantity -= $res[$unit['code']] * $unit['base_unit_quantity'];

F
forwox, 2021-08-07
@forwox

Thank you, I didn’t think that it was so easy to solve)
BUT this method does not work quite correctly:
610e24c751621420066239.png
610e25320927c457599419.png
610e25b6c487a631715795.png
In general, for some reason there is an error in the calculations, as far as I understood on the smallest unit of measurement.
What could be the problem?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question