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
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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;
}
ASKER
number_format() works fine.
Thanks
Thanks
<?php
$string = '1';
$string = sprintf('%.2f', $string);
echo $string;
?>
Output: 1.00
Cheers