PHP number format with integer format - php

I am using PHP number_format to express prices of products, using decimal point, thousands separators, etc. For example:
$price = 20.456;
print "$" . number_format($price, 2, ".", ",");
outputs $20.46.
However, I would like that, if the price is integer, for example $price = 20.00, to output $20. Is there some other function or rule to achieve this, avoiding decimal points if not necessary?

Just do a loose comparison of $price cast as integer against $price, if they match (ie. it's a whole number), you can format to 0 decimal places:
number_format($price, ((int) $price == $price ? 0 : 2), '.', ',');

You can use ternary operator fot that:
$price = 20.456;
print "$" . ($price == intval($price) ? number_format($price, 0, "", ",") : number_format($price, 2, "", ","));

Try $price = 20.456 +0 ;
$price + 0 does the trick.
echo 125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7
Internally, this is equivalent to casting to float with (float)$price or floatval( $price) but I find it simpler.

A little helper function my_format to determine if the number is an integer and then return the corresponding string.
function my_format($number)
{
if (fmod($number, 1) == 0) {
return sprintf("$%d\n", $number);
} else {
return sprintf("$%.2f\n", $number);
}
}
$price = 20.456;
echo my_format($price);
echo my_format(20);
Will output
$20.46 $20

A little solution that works for any number
$price = "20.5498";
$dec = fmod($price, 1);
if($dec > 0)
print "$" . number_format($price, 2, ".", ",");
else
print "$" . floor($price);;

You can use floor() function
$price = 20.456;
echo '$'.floor($price); // output $20

Related

How to format a decimal number based on certain values in php

I am having few values
99.00
99.90
99.01
FYI, I am already getting the above 3 values after having number_format($value, 2) applied to them
But now I want to strip the decimals without rounding them off such as
99.00 to 99
99.90 to 99.9
99.01 to 99.01 remains same
How can achieve this? Please devise me a way guys.
I just need a function which checks following:
Whether a given number is decimal i.e having "." and digits after decimal
Whether the last digit is 0, if yes, then get rid of the last digit
Whether both the digits after decimal points are 0, if yes, remove them.
If any of them are not 0, then they should remain there, like in case of 99.09 it should remain intact, in case of 99.90 it should be 99.9.
Awaiting your ideas. Thanks in advance.
By adding 0 to the number, the rightmost zeros are removed:
$num1 = 99.00;
$num2 = 99.90;
$num3 = 99.01;
$num4 = 99.012;
$num5 = 99.0123;
$num1 = number_format(99.00, 2, '.', '') + 0;
$num2 = number_format(99.90, 2, '.', '') + 0;
$num3 = number_format(99.01, 2, '.', '') + 0;
$num4 = number_format(99.012, 2, '.', '') + 0;
$num5 = number_format(99.0123, 2, '.', '') + 0;
echo "$num1\n";
echo "$num2\n";
echo "$num3\n";
echo "$num4\n";
echo "$num5\n";
Output:
99
99.9
99.01
99.01
99.01
Try it here.
With a function:
function round2no0(&$num)
{
$num = number_format($num, 2, '.', '') + 0;
}
usage:
$num1 = 99.00;
$num2 = 99.90;
$num3 = 99.01;
$num4 = 99.012;
$num5 = 99.0123;
round2no0($num1);
round2no0($num2);
round2no0($num3);
round2no0($num4);
round2no0($num5);
echo "$num1\n";
echo "$num2\n";
echo "$num3\n";
echo "$num4\n";
echo "$num5\n";
function round2no0(&$num)
{
$num = number_format($num, 2, '.', '') + 0;
}
Output:
99
99.9
99.01
99.01
99.01
Edit:
Added , '.', '' parameters to number_format to handle also numbers with thousands maintaining the machine-format 12345.12.
Try it here.
you should be able to just wrap it in a floatval()
Try this:
echo round(99.001, 2), PHP_EOL;
echo round(99.901, 2), PHP_EOL;
echo round(99.011, 2), PHP_EOL;
Output:
99
99.9
99.01
If you use a custom notation with number_format, you can use preg_replace to remove the decimal point separator and trailing zeroes after it.
// Default notation
echo preg_replace('/\.?0+$/', '', number_format(9990.00, 2)); // "9,990"
echo preg_replace('/\.?0+$/', '', number_format(9990.90, 2)); // "9,990.9"
echo preg_replace('/\.?0+$/', '', number_format(9990.01, 2)); // "9,990.01"
// French notation
echo preg_replace('/,?0+$/', '', number_format(9990.00, 2, ',', ' ')); // "9 990"
echo preg_replace('/,?0+$/', '', number_format(9990.90, 2, ',', ' ')); // "9 990,9"
echo preg_replace('/,?0+$/', '', number_format(9990.01, 2, ',', ' ')); // "9 990,01"

Modify decimal point and thousands separator without changing the number of decimals

I'm new to php and I'm trying to use number_format :
number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
As in the title, my goal is to modify decimal point and thousands separator without changing the number of decimals as below:
$Num=123456.789;
$Num2=number_format ($Num, [decimals as in $Num], ",", "'" );
My result should be:
$Num2="123'456,789";
Edit
I need a code for an unknown number of decimals
You can use NumberFormatter.
You will still need to specify a certain amount of fraction digits, but you can just use a high enough value and be fine. It's not like the number of digits is really arbitrary. It's tied to your precision ini setting.
$formatter = new NumberFormatter("en_US", NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 42);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "'");
$formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, ",");
echo $formatter->format(123456.7891234); // 123'456,7891234
Demo https://3v4l.org/TCAIA
You can do it such a way (firstly take a look to #Gordon answer – it's much more better):
<?php
function extendedNumberFormat($num, $decimalSeparator, $thousandSeparator) {
$asStr = strval($num);
$exploded = explode('.', $asStr);
$int = $exploded[0];
$decimal = isset($exploded[1]) ? $exploded[1] : null;
$result = number_format($int, 0, ".", $thousandSeparator);
if ($decimal !== null) {
$result .= $decimalSeparator . $decimal;
}
return $result;
}
echo extendedNumberFormat(123456.789, ',', "'") . "\n";
echo extendedNumberFormat(123456.7891, ',', "'") . "\n";
echo extendedNumberFormat(123456, ',', "'") . "\n";
//123'456,789
//123'456,7891
//123'456

Need to convert the floating values to integer format below the condition in php

Need to convert the floating values to integer format below the condition
$val = 75.00 means the value must be show 75
$val = 75.50 means the values must be show 75.50
the floating points values .00 means no need to display otherwise will display with floating values.
is possible in php?
Try this code:
$val = 75.00;
$value = explode(".", $val);
$decimal_value = substr($value[0], 0, 1);
if($decimal_value == "00"){
$val = $value[0];
} else {
$val = number_format($val, 2, '.', '');
}
echo $val;
$val + 0 does the trick.
echo 75.00 + 0; // 75
echo 75.50 + 0; // 75.5
Internally, this is equivalent to casting to float with (float)$val or floatval($val) but I find it simpler.
(float) $val;
In finally use below the code.
$ans = (float)$val;
echo $ans; means it working perfectly.

Add commas as thousands separator and floating point dot in php

I have this
$example = "1234567"
$subtotal = number_format($example, 2, '.', '');
the return of $subtotal is "1234567.00"
how to modify the definition of $subtotal, make it like this "1,234,567.00"
Below will output 1,234,567.00
$example = "1234567";
$subtotal = number_format($example, 2, '.', ',');
echo $subtotal;
Syntax
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
But I advise you to use money_format which will formats a number as a currency string
You have many options, but money_format can do the trick for you.
// Example:
$amount = '100000';
setlocale(LC_MONETARY, 'en_IN');
$amount = money_format('%!i', $amount);
echo $amount;
// Output:
"1,00,000.00"
Please note that money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so it is undefined in Windows.
Final edit: Here's a pure PHP Implementation that will work on any system:
$amount = '10000034000';
$amount = moneyFormatIndia( $amount );
echo number_format($amount, 2, '.', '');
function moneyFormatIndia($num){
$explrestunits = "" ;
if(strlen($num)>3){
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++){
// creates each of the 2's group and adds a comma to the end
if($i==0){
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
}else{
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return $thecash; // writes the final format where $currency is the currency symbol.
}
Ref: http://php.net/manual/en/function.money-format.php
string money_format ( string $format , float $number )
ex:
// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56
Note: The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.
Note: The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.
Use number_format : http://www.php.net/manual/en/function.number-format.php
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
$number = 123457;
$format_number = number_format($number, 2, '.', ',');
// 1,234.57

modify price variable

I'm trying to modify a variable from a form.
I want to get rid of any "," but keep the "." while changing it to "%2e"
$price = '6,000.65';
//$price = preg_replace('.', '%2e', $price);
$price = urlencode($price);
echo $price;
This is the exact result from your question:
$price = str_replace(',', '', $price);
$price = str_replace('.', '%2e', $price);
echo $price;
But why would you urlencode it...? If you want to strip unallowed characters (everything but digits and a dot), use the next function:
$price = preg_replace('/[^0-9.]/', '', $price);
// OP requested it...
$price = str_replace('.', '%2e', $price);
echo $price;
Alternatively, you can convert the string into a floating point number and use number_format() to format it nicely.
// note that numbers will be recognised as much as possible, but strings like `1e2`
// will be converted to 100. `1x2` turns into `1` and `x` in `0` You might want
// to apply preg_replace as in the second example
$price = (float)$price;
// convert $price into a string and format it like nnnn.nn
$price = number_format("$price", 2, '.', '');
echo $price;
Third option, works in a similar way. % is a special character for sprintf, marking a conversation specification. .2 tells it to have two decimals and f tells it's a floating point number.
$price = sprintf('%.2f', $price);
echo $price;
// printf combines `echo` and `sprintf`, the below code does the same
// except $price is not modified
printf('%.2f', $price);
References:
http://php.net/str-replace
http://php.net/preg-replace
http://php.net/number-format
http://php.net/sprintf
http://php.net/printf
http://php.net/manual/en/function.str-replace.php
$newPhrase = str_replace($findWhat, $replaceWith, $searchWhere);
so in your case:
$newPrice = str_replace(",", "", $price);
$price = '6,000.65';
$price = str_replace(',','',str_replace('.', '%2e',&$price));
$price = urlencode($price);

Categories