1

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)
Alex
  • 781
  • 10
  • 23

5 Answers5

0

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

Margus Pala
  • 8,433
  • 8
  • 42
  • 52
0

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
Ahmed Ziani
  • 1,206
  • 3
  • 14
  • 26
0

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.

Branimir Đurek
  • 632
  • 5
  • 13
0

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.

Mike
  • 1,968
  • 18
  • 35
-1
$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
HTMLGuy
  • 245
  • 2
  • 17
  • They want to remove the last `0` in `2.50` – Mike Apr 24 '15 at 14:49
  • Updated. I didn't catch that. – HTMLGuy Apr 24 '15 at 17:55
  • The example outputs provided do not match the actual outputs (http://ideone.com/4MnQIe), and the solution requires the use of 3 functions, 2 of which are effectively redundant (trimming 0's). It is not concise, performant or easy to understand. – Mike Apr 28 '15 at 13:58