Thejas Thejas - 2 months ago 25
PHP Question

Trim zeros from decimal part php

My exact requirement is, if the second decimal of the value is zero,
the value should only have one decimal. For others, it should have two decimal.


eg 1. 150.00 to 150.0
eg 2. 150.10 to 150.1
eg 3. 150.76 to 150.76


What I need to know is whether there is any PHP function to do this.

echo floatval("150.00")."<br>";
echo floatval("150.10")."<br>";
echo floatval("150.76")."<br>";


The result is as follows:

150
150.1
150.76


I need to have 150.0 instead of 150. I just need to know if there is any php function. Otherwise I will be able to write code.

Answer

You can use substr() function also to remove last char if it is 0. May be the below code will help you

function roundit($string)
{
 if (substr($string, -1, 1) == '0')
 {
  $string = substr($string, 0, -1);
  echo $string;
 }
 else
 echo $string;
}
roundit('150.00');
roundit('150.10');
roundit('150.76');