regex to format a float in php

Posted by Itamar Bar-Lev on Stack Overflow See other posts from Stack Overflow or by Itamar Bar-Lev
Published on 2010-05-26T12:52:35Z Indexed on 2010/05/26 13:01 UTC
Read the original article Hit count: 312

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about php

Related posts about regex