• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 206
  • Last Modified:

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
0
steva
Asked:
steva
1 Solution
 
Vimal DMSenior Software EngineerCommented:
Hai,

Can use the PHP building function,if you want can modify accordingly.

$number =1;
echo number_format($number, 2, '.', ' ');
0
 
Marco GasiFreelancerCommented:
You can use sprintf (http://it.php.net/sprintf):

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

Output: 1.00

Cheers
0
 
Mohamed AbowardaSoftware EngineerCommented:
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

0
 
stevaAuthor Commented:
number_format() works fine.

Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now