Option to exclude currency symbol from currency method #53017
Replies: 2 comments 2 replies
-
You can achieve your goal of formatting currency without displaying the currency symbol while retaining locale and other features by creating a custom wrapper around the Here's how you could implement a custom helper function to format the number as currency without the symbol: Custom Helper Function
You can create a new helper function in a file such as namespace App\Helpers;
use Illuminate\Support\Facades\Number;
class NumberHelper
{
public static function currencyWithoutSymbol($value, $currency = null, $locale = null)
{
// Format the number as currency
$formatted = Number::currency($value, $currency, $locale);
// Remove the currency symbol
return preg_replace('/[^\d.,]/', '', $formatted);
}
} Usage
Now, you can call this helper wherever you need to format the number without a currency symbol: use App\Helpers\NumberHelper;
$amount = 100;
$formattedAmount = NumberHelper::currencyWithoutSymbol($amount, 'USD', 'en_US'); // returns "100.00" Registering the HelperIf you haven't already, ensure your helper file is autoloaded. You can do this by including it in "autoload": {
"files": [
"app/Helpers/NumberHelper.php"
]
} Then run: composer dump-autoload Additional Considerations
Alternative ApproachIf you'd prefer to add this functionality directly into your existing application without a helper, consider extending the namespace App\Facades;
use Illuminate\Support\Facades\Number as BaseNumber;
class Number extends BaseNumber
{
public static function currencyWithoutSymbol($value, $currency = null, $locale = null)
{
$formatted = parent::currency($value, $currency, $locale);
return preg_replace('/[^\d.,]/', '', $formatted);
}
} In this case, you’d register your custom facade in |
Beta Was this translation helpful? Give feedback.
-
Without the currency symbol, it works pretty much like Maybe, it's interesting to not, that the class is merely a wrapper for the native You can probably create your own rule-based formatter, but that might require you to reproduce most of the existing currency formatting functionality. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I've recently started using the currency method of the Number helper. In my use case I need to commit the currency symbol but retain the locale and other currency features. I tried passing an empty value to this but id doesn't return without a symbol.
Maybe we could introduce a new feature to exclude the symbol, or a new method that wraps the function just without the symbol?
Beta Was this translation helpful? Give feedback.
All reactions