regex to format a float in php
- by Itamar Bar-Lev
I have a PHP function for formatting a float to a given amount of decimal points that uses number_format(), and then removes the unneeded zeros (and also the '.' if possible):
$float = number_format($float, $decimalPlaces, '.', '');
for ($i = 0; $i < $decimalPlaces; $i++)
{
if (substr($float, strlen($float) - 1, strlen($float)) == '0')
{
$float = substr($float, 0, strlen($float) - 1);
}
}
if (substr($float, strlen($float) - 1, strlen($float)) == '.')
{
$float = substr($float, 0, strlen($float) - 1);
}
Is it possible to do so more effectively with a regular expression?