Formatting Numbers

I l @ ve RuBoard

Formatting Numbers

Although your calculator is on its way to being practical, you still have one legitimate problem: you cannot ask someone to make a monthly payment of $521.16666666667. In order to create a more usable number as your monthly payment, you will make your total cost an easily divisible number. To do this, you use the printf() function, which prints a formatted number according to your specifications.

To use printf(), you feed it a format and a string (or number). For example, to print out an amount variable in the form of a floating-point number with two digits to the right of the decimal (e.g., 1.02 ), you would code:

 printf ("%01.2f", $Amount); 

The "%01.2f" segment tells PHP to print the $Amount using 0 to pad extra spaces, with at least one digit to the left of the decimal and with two digits to the right of the decimal. There are more complicated uses of printf(), but this will be more than sufficient for your need to make legitimate dollar amounts.

To use printf():

  1. Open numbers.php in your text editor.

  2. Change line 17 to read (Script 4.2):

     print ("The total with tax, minus   your $$Discount, comes to $");   printf ("%01.2f", $TotalCost); 
    Script 4.2. The printf() function will print the numbers formatted according to certain specifications, creating more logical numbers.

    graphics/04sc02.jpg

    To use printf(), you'll want to separate the majority of the print() statements from the one that handles the formatting.

  3. Change line 18 to read:

     print (".\n<P>You may purchase   the widget(s)in 12 monthly   installments of $"); printf ("%01.2f", $Payments); print (" each.\n<P>"); 

    You'll do the same thing to line 18 as you did to line 17. The original one line of code will become three but it will produce better results.

  4. Save the file, upload it to your server, and test in your browser (Figure 4.3).

    Figure 4.3. Your updated version of the script gives you better numbers for monthly payments (although at your expense) than it did before (see Figure 4.1) now that it incorporates the printf() function.

    graphics/04fig03.jpg

Tip

A parallel to the printf() function is the sprintf() function. It works the same only printf() will actually send the results to the browser whereas k sprintf() changes a variable without printing it.

 $Amount = sprintf ("%01.2f",   $Amount); 

I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net