Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -439,4 +439,24 @@ protected static function ensureIntlExtensionIsInstalled()
throw new RuntimeException('The "intl" PHP extension is required to use the ['.$method.'] method.');
}
}

/**
* Format a number as a percentage with custom precision.
*
* @param float|int $number
* @param int $precision
* @param string|null $locale
* @return string|false
*/
public static function formatPercentage($number, $precision = 2, $locale = null)
{
if (!is_numeric($number)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔷 Medium: The current input validation only checks if the input is numeric. Consider throwing an exception for non-numeric input to align with the class's error-handling practices and provide clearer feedback to the caller.

return false;
}

$formatter = new NumberFormatter($locale ?? app()->getLocale(), NumberFormatter::PERCENT);
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);

return $formatter->format($number / 100);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔷 Medium: The division by 100 assumes the input is a percentage value (e.g., 12.34 becomes 0.1234). Ensure this behavior is documented and consistent with the method's intent.

Suggested change
return $formatter->format($number / 100);
return $formatter->format($number);

}
}