Print Currency Number Format in PHP - php

I have some price values to display in my page.
I am writing a function which takes the float price and returns the formatted currency val with currency code too..
For example, fnPrice(1001.01) should print $ 1,000.01

The easiest answer is number_format().
echo "$ ".number_format($value, 2);
If you want your application to be able to work with multiple currencies and locale-aware formatting (1.000,00 for some of us Europeans for example), it becomes a bit more complex.
There is money_format() but it doesn't work on Windows and relies on setlocale(), which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.
If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.

with the intl extension in PHP 5.3+, you can use the NumberFormatter class:
$amount = '12345.67';
$formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
which prints :
UK: €12,345.67
DE: 12.345,67 €

sprintf() is the PHP function for all sorts of string formatting
http://php.net/manual/en/function.sprintf.php
I use this function:
function formatDollars($dollars){
return '$ '.sprintf('%0.2f', $dollars);
}

I built this little function to automatically format anything into a nice currency format.
function formatDollars($dollars)
{
return "$".number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)),2);
}
Edit
It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:
function formatDollars($dollars)
{
$formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
return $dollars < 0 ? "({$formatted})" : "{$formatted}";
}

Reference Link : https://www.php.net/manual/en/function.number-format.php
$amount = 1235.56
echo number_format($amount, 2, '.', ',');
The output is : 1,235.56
If you don't need comma in output.Please remove comma inside function.
For example
$amount = 1235.56
echo number_format($amount, 2, '.', '');
The output is : 1235.56

From the docs
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>

PHP has a function called money_format for doing this. Read about this here.

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
output will be
1.234.567,89 €
1.234.567,89 RUR
https://www.php.net/manual/en/numberformatter.formatcurrency.php

Related

I am struggling with PHP number formatting

I am extremely new to PHP, and I am having some issues with the number_format() function.
I am performing a calculation which is, correctly, returning this result: 6215.
However, I want this value to be displayed/echoed as 62.15. I have played around with the number_format() function to no avail.
Any help would be greatly appreciated!
You have 2 potential tasks here.
1.) You want to change your number (divide by 100)
<?php
$number = 6215;
$number = $number / 100;
echo $number;
?>
Renders as 62.15
2.) You may want additional formatting to make a "pretty" number
From the docs: https://www.php.net/manual/en/function.number-format.php
// Function signature syntax
number_format(
float $num,
int $decimals = 0,
?string $decimal_separator = ".",
?string $thousands_separator = ","
)
<?php
$number = 1006215.56;
$pretty_number = number_format($number, 2, '.', '');
echo $pretty_number;
?>
Renders as 1,006,215.56
This was directly pulled from the php.net documentation, which I think is really great.
https://www.php.net/manual/en/function.number-format.php
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>

How to show number string value with plus or minus

I am trying to get number value with plus and minus
<?php
$num1= '-12.20000';
$num2= '+18.20000';
echo rtrim(str_replace('.00', '', number_format($num1, 2));
echo rtrim(str_replace('.00', '', number_format($num2, 2));
?>
Need output like
-12.2
+18.2
I can't see exactly what you need. There are not enough examples and your description of the task is not sufficient.
The number is formatted with a sign and 2 decimal places. If the last digit is a 0, it is removed with preg_replace().
$data = ['-12.20000','+18.20000', 234.0, 2.1234];
foreach($data as $value){
$formatVal = sprintf("%+0.2f",$value);
$formatVal = preg_replace('~(\.\d)0$~','$1',$formatVal);
echo $value.' -> '.$formatVal."<br>\n";
}
Output:
-12.20000 -> -12.2
+18.20000 -> +18.2
234 -> +234.0
2.1234 -> +2.12
If the result is only ever required with one decimal place, you can use
$formatVal = sprintf("%+0.1f",$value);
without the preg_replace.
In python, you could do it like this:
def returnWithSign(str):
n = float(str)
if n>0:
return '+{}'.format(n)
return n
Instead of using difficult functions in PHP just use the native stuff PHP brings with it. One fantastic thing of that stuff is the NumberFormatter class.
$formatter = new NumberFormatter( 'en_GB', NumberFormatter::DECIMAL );
$formatter->setTextAttribute(NumberFormatter::POSITIVE_PREFIX, '+');
$num1= '-12.20000';
$num2= '+18.20000';
echo $formatter->format($num1) . PHP_EOL;
echo $formatter->format($num2) . PHP_EOL;
Exactly does what you want.
Output: https://3v4l.org/UQX3Y

How can I check if number has one , or two decimals?

I would like to know how I can check if a number has one or two decimals, and if it only has one decimal , like 12,9 for example, then echo the number with an additional 0, so it looks like 12,90.
<?php
$number = '12,9';
if $number //has 2 decimals // {
echo $number; }
else {
echo $number.'0';
}
endif;
?>
I have no clue how to do that properly, any help would be really appreciated! Thanks
If your input is a . (dot) separated decimal, you can just use number_format():
number_format('12.9', 2);
Alternatively, you can use the NumberFormatter class if you need to support multiple locales or numbers with commas for decimal separators. Such as:
$formatter = new NumberFormatter('de_DE', NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $formatter->format($formatter->parse('12,9'));
Note: The use of NumberFormatter requires the intl extension. It can be added on debian based systems with a simple sudo apt-get install php5-intl.
If you're sure that the number is always formatted like you've posted, than you could do:
number_format(str_replace(',', '.', '12,9'), 2, ',', '.');
what you need is the number_format function
http://www.php.net/manual/en/function.number-format.php
Since PHP is not strictly typed, you could so something like this:
$parts = explode(",", $number);
$num_decimals = strlen($parts[1]);
if ($num_decimals == 2) //has 2 decimals // {
echo $number;
} else {
echo $number.'0';
}

In PHP, how to print a number with 2 decimals, but only if there are decimals already?

I have a basic index.php page with some variables that I want to print in several places - here are the variables:
<?php
$firstprice = 1.50;
$secondprice = 3.50;
$thirdprice = 20;
?>
My challenge is that later in the document, when I print, I get the prices without the second '0' in the price - this is what happens:
<?php print "$firstprice";?> // returns 1.5 - not 1.50!
SO - I know how to do this with JS, but how is this done in PHP 5+? Basically I want to print the second '0' if there is already a decimal, so if the variable is equal to '3', it stays as '3', but if it's equal to '3.5' it converts to display '3.50' with a second '0', etc.
Here's a JS example - what's the PHP equivalent?
JS:
.toFixed(2).replace(/[.,]00$/, ""))
Many thanks!!
This is simple and it will also let you tweak the format to taste:
$var = sprintf($var == intval($var) ? "%d" : "%.2f", $var);
It will format the variable as an integer (%d) if it has no decimals, and with exactly two decimal digits (%.2f) if it has a decimal part.
See it in action.
Update: As Archimedix points out, this will result in displaying 3.00 if the input value is in the range (2.995, 3.005). Here's an improved check that fixes this:
$var = sprintf(round($var, 2) == intval($var) ? "%d" : "%.2f", $var);
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
more info here
http://php.net/manual/en/function.number-format.php
You could use
if (is_float($var))
{
echo number_format($var,2,'.','');
}
else
{
echo $var;
}
What about something like this :
$value = 15.2; // The value you want to print
$has_decimal = $value != intval($value);
if ($has_decimal) {
echo number_format($value, 2);
}
else {
echo $value;
}
Notes :
You can use number_format() to format value to two decimals
And if the value is an integer, just display it.
you can use number_format():
echo number_format($firstprice, 2, ',', '.');
Alternatively way to print
$number = sprintf('%0.2f', $numbers);
// 520.89898989 -> 520.89

How do I format a number to a dollar amount in PHP

How do you convert a number to a string showing dollars and cents?
eg:
123.45 => '$123.45'
123.456 => '$123.46'
123 => '$123.00'
.13 => '$0.13'
.1 => '$0.10'
0 => '$0.00'
If you just want something simple:
'$' . number_format($money, 2);
number_format()
PHP also has money_format().
Here's an example:
echo money_format('$%i', 3.4); // echos '$3.40'
This function actually has tons of options, go to the documentation I linked to to see them.
Note: money_format is undefined in Windows.
UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php
WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.
Instead, look into NumberFormatter::formatCurrency.
$number = "123.45";
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($number, 'USD');
i tried money_format() but it didn't work for me at all. then i tried the following one. it worked perfect for me. hopefully it will work in right way for you too.. :)
you should use this one
number_format($money, 2,'.', ',')
it will show money number in terms of money format up to 2 decimal.
In PHP and C++ you can use the printf() function
printf("$%01.2f", $money);
Note that in PHP 7.4, money_format() function is deprecated. It can be replaced by the intl NumberFormatter functionality, just make sure you enable the php-intl extension. It's a small amount of effort and worth it as you get a lot of customizability.
$f = new NumberFormatter("en", NumberFormatter::CURRENCY);
$f->formatCurrency(12345, "USD"); // Outputs "$12,345.00"
The fast way that will still work for 7.4 is as mentioned by Darryl Hein:
'$' . number_format($money, 2);
In php.ini add this (if it is missing):
#windows
extension=php_intl.dll
#linux
extension=php_intl.so
Then do this:
$amount = 123.456;
// for Canadian Dollars
$currency = 'CAD';
// for Canadian English
$locale = 'en_CA';
$fmt = new \NumberFormatter( $locale, \NumberFormatter::CURRENCY );
echo $fmt->formatCurrency($amount, $currency);
/* Just Do the following, */
echo money_format("%(#10n","123.45"); //Output $ 123.45
/* If Negative Number -123.45 */
echo money_format("%(#10n","-123.45"); //Output ($ 123.45)

Categories