You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RateCalculator.php 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Utilities;
  3. use App\Enums\Setting\NumberFormat;
  4. use App\Models\Setting\Localization;
  5. class RateCalculator
  6. {
  7. public const PRECISION = 4;
  8. public const SCALING_FACTOR = 10 ** self::PRECISION;
  9. public const PERCENTAGE_SCALING_FACTOR = self::SCALING_FACTOR * 100;
  10. public static function calculatePercentage(int $value, int $scaledRate): int
  11. {
  12. return (int) round(($value * $scaledRate) / self::PERCENTAGE_SCALING_FACTOR);
  13. }
  14. public static function scaledRateToDecimal(int $scaledRate): float
  15. {
  16. return $scaledRate / self::PERCENTAGE_SCALING_FACTOR;
  17. }
  18. public static function decimalToScaledRate(float $decimalRate): int
  19. {
  20. return (int) round($decimalRate * self::PERCENTAGE_SCALING_FACTOR);
  21. }
  22. public static function parseLocalizedRate(?string $value): int
  23. {
  24. if (! $value) {
  25. return 0;
  26. }
  27. $format = Localization::firstOrFail()->number_format->value;
  28. [$decimalMark, $thousandsSeparator] = NumberFormat::from($format)->getFormattingParameters();
  29. $floatValue = (float) str_replace([$thousandsSeparator, $decimalMark], ['', '.'], $value);
  30. return (int) round($floatValue * self::SCALING_FACTOR);
  31. }
  32. public static function formatScaledRate(int $scaledRate): string
  33. {
  34. $format = Localization::firstOrFail()->number_format->value;
  35. [$decimalMark, $thousandsSeparator] = NumberFormat::from($format)->getFormattingParameters();
  36. $percentageValue = $scaledRate / self::SCALING_FACTOR;
  37. $formatted = number_format($percentageValue, self::PRECISION, $decimalMark, $thousandsSeparator);
  38. $formatted = rtrim($formatted, '0');
  39. return rtrim($formatted, $decimalMark);
  40. }
  41. }