views:

47

answers:

3

I'm looking for a way to use the php number_format function or something similar that will add the thousand seperator but will leave any decimal part of the number intatct without and formatting of this. For example:

39845.25843 => 39,845.25843

347346.8 => 347,346.8

1000000 = > 1,000,000

Thanks

+1  A: 

I'm with little imagination for variable names, but this will do:

function conv($str) {
    $t = explode(".", $str);
    $ret = number_format(reset($t), 0);
    if (($h = next($t)) !== FALSE)
        $ret .= "." . $h;
    return $ret;
}
Artefacto
+1  A: 
$val = number_format($val, strlen(end(explode('.', $val))));

Edit: if you want to handle integers also the above won't work without adding a case for no decimal

$val = number_format( $val, (strstr($val, '.')) ? strlen(end(explode('.', $val))) : 0 );
Rob
A: 

same as above but my twist:

function mod_numberformat($num){
    // find & cache decimal part
    $pos = strpos($num, '.');
    $decimal = $pos !== false ? substr($num, $pos) : '';

    // format number & avoid rounding
    $number = number_format($num, 9);

    // strip new decimal part & concatenate cached part
    $number = substr($number, 0, strpos($number, '.'));
    $number .= $decimal;

    return $number;
}
Alex