Specifying a format for a string variable.

Posted on 2011-04-29
Last Modified: 2012-05-11
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?

Question by:steva
    LVL 7

    Accepted Solution


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

    $number =1;
    echo number_format($number, 2, '.', ' ');
    LVL 30

    Expert Comment

    by:Marco Gasi
    You can use sprintf (

    $string = '1';
    $string = sprintf('%.2f', $string);
    echo $string;

    Output: 1.00

    LVL 12

    Expert Comment

    by:Mohamed Abowarda
    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; 
            return (int)$formatted; 

    Open in new window


    Author Closing Comment

    number_format() works fine.


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
    Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    7 Experts available now in Live!

    Get 1:1 Help Now