I try to remove zero number from php variable using php function, but not work.
I try to use round
or floor
or ceil
but not work.
How can I do that?
2.00 ===> 2
2.05 ===> 2.05 (not remove zero)
2.50 ===> 2.5
2.55 ===> 2.55 (not remove zero)
I try to remove zero number from php variable using php function, but not work.
I try to use round
or floor
or ceil
but not work.
How can I do that?
2.00 ===> 2
2.05 ===> 2.05 (not remove zero)
2.50 ===> 2.5
2.55 ===> 2.55 (not remove zero)
You must be having string variable. Please convert it to float as (float)$var and you will lose these zeros if you print the result out.
Other option is to use rtrim on string to remove the 0 and . from the end. see examples here http://php.net/rtrim
Try this :
$list = array("2.00", "2.05", "2.50", "2.55");
foreach($list as $val)
echo (double) $val . "</br>";
Output:
2
2.05
2.5
2.55
Try this:
number_format((float)$your_number, 2, '.', '');
I had the same problem. Function number_format() returns number as string so it will not remove zeros at the end.
In PHP you can cast the value to a Float Type (double, float, real), which will drop all leading or trailing zeros (after the decimal).
2.5 === (double) "2.50"
Be aware, however, that this does not format your number other than removing the 0's (this does not ensure a money format). For formatting, see number_format().
2.5 === (double) number_format('2.501', 2, '.', '');
Example:
(float) 2.00 === 2
(float) 2.05 === 2.05 // (not remove zero)
(float) 2.50 === 2.5
(float) 2.55 === 2.55 // (not remove zero)
And a proof: http://ideone.com/wimBHm
An interesting thing to note is that the test (float) 2.00 === 2
actually does not pass, this is because 2
is actually of type (int)
, and therefore fails the ===
test, however, as you can see, the output is exactly what you are looking for.
$price = '2.00';
$price2 = '2.50';
$price3 = '2.05';
function formatPrice($price)
{
/* Format number with 2 decimal places, then remove .00, then right trim any 0 */
return rtrim(str_replace('.00', '', number_format($price, 2)), '0');
}
echo formatPrice($price); //2
echo formatPrice($price2); //2.5
echo formatPrice($price3); //2.05