I have flights and need to display the expected amount, e.g. parcel_1_weight = 5, parcel_2_weight = 0.2, e.g. 1kg = 28.88, I need 5.2 * 28.88.
I also have a single price for each parcel.
this is my code
class FlightTotal
{
public static function payable($parcels)
{
$unpaidParcels = $parcels->where('is_paid', 0);
$payable = [...$unpaidParcels->map(function ($unpaidParcel) {
return PriceCalculator::calculatePrice($unpaidParcel->volume_weight && $unpaidParcel->volume_weight != '0.00' ? $unpaidParcel->volume_weight : $unpaidParcel->physical_weight, $unpaidParcel->flight?->remoteAddress->id, $unpaidParcel->user->id, $unpaidParcel->user->type);
})];
return array_sum($payable);
}
public static function amount($parcels)
{
$paidParcels = $parcels->where('is_paid', 1);
$totalPaidAmount = 0;
foreach ($paidParcels as $paidParcel) {
$totalPaidAmount += abs($paidParcel->price);
}
return self::payable($parcels) + $totalPaidAmount;
}
}
class PriceCalculator
{
public static function custom_number_format($price, $weight)
{
$formatted = number_format($price * $weight, 2, '.', '');
if ($formatted > 1000 && substr($formatted, -3) == '.00') {
$formatted = substr($formatted, 0, -3);
}
return $formatted;
}
public static function calculatePrice($weight, $remoteAddressId, $userId, $organisation)
{
$organisation = $organisation == 'individual' ? 0 : 1;
$personalPrice = PersonalPrice::where('remote_address_id', $remoteAddressId)
->where('user_id', $userId)
->first();
$priceRange = PriceRange::where('remote_address_id', $remoteAddressId)
->where('from', '<=', $weight)
->where('to', '>=', $weight)
->where('organisation', $organisation)
->first();
$remoteAddress = RemoteAddress::findOrFail($remoteAddressId);
if ($personalPrice) {
return number_format($personalPrice->price * $weight, 2);
}
if ($priceRange) {
return number_format($priceRange->price * $weight, 2);
}
if ($organisation == 0) {
return self::custom_number_format($remoteAddress->rest_price, $weight);
} else {
return self::custom_number_format($remoteAddress->organisation_rest_price, $weight);
}
}
}
Now when I have 21 parcel total weight 9.6 it calculated as 277.27 instead of 277.248 if we rounded it 277.25 not .27.
In the second flight have total weight 249.09 and calculated as 7193.88 instead of 7193.7192
The ChatGPT recommends that I use BCMath or GMP Libraries but it return same results