Add formatPercentage method to Number class#1
Conversation
Adds a new method to format numbers as percentages with customizable precision and locale support.
WalkthroughAdds a new public static method Number::formatPercentage($number, $precision = 2, $locale = null) that validates numeric input, formats it as a localized percentage using Intl NumberFormatter::PERCENT with specified fraction digits after dividing the value by 100, and returns false for non-numeric input. It does not call ensureIntlExtensionIsInstalled(). Changes
Sequence Diagram(s)sequenceDiagram
actor Caller
participant Number as Number::formatPercentage
participant Intl as Intl\NumberFormatter (PERCENT)
Caller->>Number: formatPercentage(number, precision, locale?)
alt Non-numeric input
Number-->>Caller: false
else Numeric input
Note over Number,Intl: create formatter with locale (or app()->getLocale())
Number->>Intl: new(locale, PERCENT)
Number->>Intl: setAttribute(FRACTION_DIGITS, precision)
Number->>Intl: format(number / 100)
Intl-->>Number: formatted string
Number-->>Caller: formatted percentage
end
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/Illuminate/Support/Number.php (2)
444-451: Clarify doc to state the input is a ratio (0..1)Matches the usage examples and avoids confusion with
percentage()which accepts percentage points.- * Format a number as a percentage with custom precision. + * Format a ratio (0..1) as a localized percentage with custom precision.
451-451: Optional: support maxPrecision to mirrorpercentage()Keeps API symmetry with existing method.
- public static function formatPercentage(int|float $number, int $precision = 2, ?string $locale = null) + public static function formatPercentage(int|float $number, int $precision = 2, ?int $maxPrecision = null, ?string $locale = null) @@ - return static::percentage($number * 100, $precision, null, $locale); + return static::percentage($number * 100, $precision, $maxPrecision, $locale);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/Illuminate/Support/Number.php(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/Illuminate/Support/Number.php (1)
src/Illuminate/Foundation/helpers.php (1)
app(132-139)
| public static function formatPercentage($number, $precision = 2, $locale = null) | ||
| { | ||
| if (!is_numeric($number)) { | ||
| return false; | ||
| } | ||
|
|
||
| $formatter = new NumberFormatter($locale ?? app()->getLocale(), NumberFormatter::PERCENT); | ||
| $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision); | ||
|
|
||
| return $formatter->format($number / 100); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Fix percentage math, remove app() coupling, align types, and reuse existing API
As written, 0.1234 formats to 0.12% (you divide by 100 before PERCENT formatting). Intl percent expects a ratio (0..1). Also, prefer class-level locale handling and typed params. Delegate to percentage() for consistency and to get the intl guard for free.
- public static function formatPercentage($number, $precision = 2, $locale = null)
- {
- if (!is_numeric($number)) {
- return false;
- }
-
- $formatter = new NumberFormatter($locale ?? app()->getLocale(), NumberFormatter::PERCENT);
- $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
-
- return $formatter->format($number / 100);
- }
+ public static function formatPercentage(int|float $number, int $precision = 2, ?string $locale = null)
+ {
+ // Accepts a ratio (e.g., 0.1234 => "12.34%"); delegate for consistent behavior.
+ return static::percentage($number * 100, $precision, null, $locale);
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public static function formatPercentage($number, $precision = 2, $locale = null) | |
| { | |
| if (!is_numeric($number)) { | |
| return false; | |
| } | |
| $formatter = new NumberFormatter($locale ?? app()->getLocale(), NumberFormatter::PERCENT); | |
| $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision); | |
| return $formatter->format($number / 100); | |
| } | |
| public static function formatPercentage(int|float $number, int $precision = 2, ?string $locale = null) | |
| { | |
| // Accepts a ratio (e.g., 0.1234 => "12.34%"); delegate for consistent behavior. | |
| return static::percentage($number * 100, $precision, null, $locale); | |
| } |
🤖 Prompt for AI Agents
In src/Illuminate/Support/Number.php around lines 451–461, the method
incorrectly divides by 100 (Intl percent expects a 0..1 ratio), is tightly
coupled to app()->getLocale(), and uses untyped parameters instead of reusing
the existing percentage() API; change the signature to typed numeric input (e.g.
float|int $number, int $precision = 2, ?string $locale = null), remove any
direct app() calls and defer locale resolution to the class-level handling, and
replace the formatting logic by delegating to the existing percentage($number,
$precision, $locale) method (which already enforces the Intl guard and correct
scaling), preserving the existing non-numeric return behavior.
| { | ||
| if (!is_numeric($number)) { | ||
| return false; | ||
| } | ||
|
|
||
| $formatter = new NumberFormatter($locale ?? app()->getLocale(), NumberFormatter::PERCENT); | ||
| $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
If keeping direct formatter code: add intl guard and use class locale
Only if you decide not to delegate to percentage().
- public static function formatPercentage($number, $precision = 2, $locale = null)
+ public static function formatPercentage(int|float $number, int $precision = 2, ?string $locale = null)
{
- if (!is_numeric($number)) {
- return false;
- }
+ static::ensureIntlExtensionIsInstalled();
- $formatter = new NumberFormatter($locale ?? app()->getLocale(), NumberFormatter::PERCENT);
+ $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::PERCENT);
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision);
- return $formatter->format($number / 100);
+ return $formatter->format($number); // expects ratio (0..1)
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| { | |
| if (!is_numeric($number)) { | |
| return false; | |
| } | |
| $formatter = new NumberFormatter($locale ?? app()->getLocale(), NumberFormatter::PERCENT); | |
| $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision); | |
| public static function formatPercentage(int|float $number, int $precision = 2, ?string $locale = null) | |
| { | |
| static::ensureIntlExtensionIsInstalled(); | |
| $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::PERCENT); | |
| $formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $precision); | |
| return $formatter->format($number); // expects ratio (0..1) | |
| } |
🤖 Prompt for AI Agents
In src/Illuminate/Support/Number.php around lines 452 to 458, add a guard that
ensures the intl extension/NumberFormatter class is available before creating a
NumberFormatter (e.g., if (!class_exists(\NumberFormatter::class)) throw new
\RuntimeException('ext-intl is required')); and replace the direct call to
app()->getLocale() with the class-level locale (use static::$locale or a
dedicated static property/method) falling back to app()->getLocale() if the
class locale is null; keep the rest of the formatter setup (PERCENT,
FRACTION_DIGITS) unchanged.
Codoki PR ReviewSummary: Delegate formatPercentage to the existing percentage method for consistency. Issues (Critical & High only)
Key Feedback (click to expand)
Confidence: 3/5 — Needs work before merge (1 high · status: Requires changes) React with 👍 or 👎 if you found this review useful. |
| * | ||
| * @param float|int $number | ||
| * @param int $precision | ||
| * @param string|null $locale |
There was a problem hiding this comment.
php
public static function formatPercentage($number, $precision = 2, $locale = null)
{
return static::percentage($number, $precision, null, $locale);
}
This PR adds a new
formatPercentagemethod to the Number class that allows formatting numbers as percentages with customizable precision and locale support.Features
Usage