Link to home
Start Free TrialLog in
Avatar of steva
steva

asked on

Specifying a format for a string variable.

A string variable I'm passing to PayPal has to have a decimal point and two places to the right.  So 1 becomes 1.00.  How can cause this format to be generated for a variable?  I know printf will generate this output, but is there a way I can just form the string I want in the variable?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Vimal DM
Vimal DM
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can use sprintf (http://it.php.net/sprintf):

<?php
$string = '1';
$string = sprintf('%.2f', $string);
echo $string;
?>

Output: 1.00

Cheers
Try the following function (improved):
function toNumber ($string, $decimal = 0) { 
    $decimal = (int)$decimal; 
    if (!is_numeric($string)) 
        return 0; 
    $formatted = sprintf('%01.'.$decimal.'f', $string); 
    if ($decimal > 0) 
        return (double)$formatted; 
    else 
        return (int)$formatted; 
}

Open in new window

Avatar of steva
steva

ASKER

number_format() works fine.

Thanks