php-unit-conversion icon indicating copy to clipboard operation
php-unit-conversion copied to clipboard

nearest does sometimes throw exception with custom set of available units

Open Gummibeer opened this issue 5 years ago • 3 comments

I've adjusted the registered units

UnitMap::clear();
UnitMap::add(Meter::class);
UnitMap::add(CentiMeter::class);
UnitMap::add(MilliMeter::class);

But now the nearest() helper fails sometimes.

Length::nearest(1, Metric::class);

Gummibeer avatar Feb 20 '20 16:02 Gummibeer

We've overridden this method in our app by a different logic and this works pretty well, for us.

We convert into all possible units (type and system as required), sort the converted values ascending and take the first >= 1 and if there's none we return the last one of the sorted ones.

This will always return the one that's grater or equal one and the lowest number of all conversions or the one with the highest value. This algorithm passes all of our tests - even with an adjusted set of units.

Gummibeer avatar Feb 20 '20 16:02 Gummibeer

Whats the exact error that occurs?

pimlie avatar Feb 23 '20 12:02 pimlie

This exception is thrown. https://github.com/pimlie/php-unit-conversion/blob/a12cdb37e09bef998a8991d81da84a0c70381560/src/Unit.php#L365

Gummibeer avatar Feb 23 '20 14:02 Gummibeer