Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RateCalculator.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. $result = ($value * $scaledRate) / self::PERCENTAGE_SCALING_FACTOR;
  13. return (int) round($result, 0, PHP_ROUND_HALF_EVEN);
  14. }
  15. public static function scaledRateToDecimal(int $scaledRate): float
  16. {
  17. return $scaledRate / self::PERCENTAGE_SCALING_FACTOR;
  18. }
  19. public static function decimalToScaledRate(float $decimalRate): int
  20. {
  21. return (int) round($decimalRate * self::PERCENTAGE_SCALING_FACTOR);
  22. }
  23. public static function parseLocalizedRate(?string $value): int
  24. {
  25. if (! $value) {
  26. return 0;
  27. }
  28. $format = Localization::firstOrFail()->number_format->value;
  29. [$decimalMark, $thousandsSeparator] = NumberFormat::from($format)->getFormattingParameters();
  30. $floatValue = (float) str_replace([$thousandsSeparator, $decimalMark], ['', '.'], $value);
  31. return (int) round($floatValue * self::SCALING_FACTOR);
  32. }
  33. public static function formatScaledRate(int $scaledRate): string
  34. {
  35. $format = Localization::firstOrFail()->number_format->value;
  36. [$decimalMark, $thousandsSeparator] = NumberFormat::from($format)->getFormattingParameters();
  37. $percentageValue = $scaledRate / self::SCALING_FACTOR;
  38. $formatted = number_format($percentageValue, self::PRECISION, $decimalMark, $thousandsSeparator);
  39. $formatted = rtrim($formatted, '0');
  40. return rtrim($formatted, $decimalMark);
  41. }
  42. }