Add zero to before decimal point of a number

爷,独闯天下 提交于 2021-01-28 05:01:54

问题


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>

回答1:


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.




回答2:


Floatval()
http://php.net/manual/en/function.floatval.php
Returns the float value of a string. No need for number format or ifs.
Floatval will also handle negative numbers such as "-.96".

$s = ".96";
Echo floatval($s);

https://3v4l.org/Qt8A3



来源:https://stackoverflow.com/questions/45530636/add-zero-to-before-decimal-point-of-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!