Skip to content

Add formatPercentage method to Number class#1

Open
zaibkhan wants to merge 5 commits into
12.xfrom
feature-number-fix
Open

Add formatPercentage method to Number class#1
zaibkhan wants to merge 5 commits into
12.xfrom
feature-number-fix

Conversation

@zaibkhan

@zaibkhan zaibkhan commented Aug 29, 2025

Copy link
Copy Markdown
Owner

This PR adds a new formatPercentage method to the Number class that allows formatting numbers as percentages with customizable precision and locale support.

Features

  • Customizable precision for decimal places
  • Locale-aware formatting
  • Input validation for numeric values

Usage

Number::formatPercentage(0.1234, 2); // "12.34%"
Number::formatPercentage(0.5, 0);    // "50%"

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

* **New Features**
  * Added a percentage-formatting utility that converts numeric percentage point values (e.g., 12.5"12.5%") into localized strings.
  * Supports configurable decimal precision and an optional locale, defaulting to the application's current locale.
  * Returns a clear failure response for invalid (non-numeric) inputs.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Adds a new method to format numbers as percentages with customizable precision and locale support.
@coderabbitai

coderabbitai Bot commented Aug 29, 2025

Copy link
Copy Markdown

Walkthrough

Adds 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

Cohort / File(s) Summary of Changes
Number percentage formatting
src/Illuminate/Support/Number.php
Added public static function formatPercentage($number, $precision = 2, $locale = null) which: validates numeric input (returns false if not numeric); constructs an Intl\NumberFormatter with PERCENT style (uses app()->getLocale() if $locale is null); sets FRACTION_DIGITS to $precision; formats ($number / 100); does not call ensureIntlExtensionIsInstalled() within the method.

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
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I hop through digits, soft and light,
I turn 75 into “75%” just right.
With whiskers set to locale tune,
Two decimals hum a gentle tune.
A crunchy carrot, formatted bright. 🥕✨

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 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.

📥 Commits

Reviewing files that changed from the base of the PR and between fb61c17 and 39dd260.

📒 Files selected for processing (1)
  • src/Illuminate/Support/Number.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Illuminate/Support/Number.php
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature-number-fix

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 mirror percentage()

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 262168a and ccf7ca4.

📒 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)

Comment on lines +451 to +461
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);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

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.

Suggested change
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.

Comment on lines +452 to +458
{
if (!is_numeric($number)) {
return false;
}

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Suggested change
{
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.

Repository owner deleted a comment from codoki-pr-intelligence Bot Aug 31, 2025
Repository owner deleted a comment from codoki-pr-intelligence Bot Aug 31, 2025
Repository owner deleted a comment from codoki-pr-intelligence Bot Aug 31, 2025
Repository owner deleted a comment from codoki-pr-intelligence Bot Aug 31, 2025
Repository owner deleted a comment from codoki-pr-intelligence Bot Sep 2, 2025
Repository owner deleted a comment from codoki-pr-intelligence Bot Sep 2, 2025
Repository owner deleted a comment from codoki-pr-intelligence Bot Sep 2, 2025
Repository owner deleted a comment from codoki-pr-intelligence Bot Sep 2, 2025
@zaibkhan

zaibkhan commented Sep 2, 2025

Copy link
Copy Markdown
Owner Author

Codoki PR Review

Summary: Delegate formatPercentage to the existing percentage method for consistency.
What’s good: The new method aligns with the existing class structure and uses locale-aware formatting.
Review Status: ❌ Requires changes
Overall Priority: High

Issues (Critical & High only)

Severity Issue Why it matters File
High Maintainability — Delegate formatPercentage to percentage method Delegate the formatPercentage method to the existing percentage method to ensure consistent behavior and reuse existing logic. …/Support/Number.php
Key Feedback (click to expand)
  • Needs improvement: Delegate to the existing percentage method to maintain consistency and reuse existing logic.
  • Testing: Consider adding tests to ensure the delegation maintains expected behavior.
  • Documentation: Document the formatPercentage method to clarify its relationship with the percentage method.
  • Compatibility: Ensure the delegation does not alter the expected output format.
  • Performance: Delegating to the existing method may improve maintainability without impacting performance.
  • Security: Ensure input validation is consistent with the existing percentage method.
  • Open questions: Is there a specific reason for not using the existing percentage method?

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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

⚠️ High: Delegate the formatPercentage method to the existing percentage method to ensure consistent behavior and reuse existing logic.

php
public static function formatPercentage($number, $precision = 2, $locale = null)
{
return static::percentage($number, $precision, null, $locale);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant