问题
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