Search code examples
phpwordpressformattingleading-zero

Add zero to before decimal point of a number


How do we we add a zero in front of the decimal place in PHP?

I want to convert .96 to 0.96

Now in my php code, I'm fetching data by using wordpress get_attribute

<td><?php echo $_product->get_attribute('pa_carat');?></td>

Solution

  • The function you want is number_format

    echo number_format(0.96, 2);
    

    Alternatively you can just check for and prepend it if it is missing.

    if ($num[0] == '.')
      $num = '0' . $num;
    

    This wont handle negative numbers though, you would need to write a little more logic for that.