Perl: decimal formatting using printf and sprintf

Tutoring math, a likely destination of some of your students is computer science. The tutor continues coverage of the Perl language, which seems flush with simple solutions to programming problems….

 
In yesterday’s post, which was about Perl subroutines, I introduced an example program that calculates the final price of an item from its sticker price, the discount, and the tax rate.

In my context, anyway, the program works great – but any zealots who typed and ran it on Boxing Day noticed that it does not format the answers as a cash register would. For example, if you give it the inputs

price: 78
discount: 33
tax rate: 12

it will give back

final price: 58.5312

Prices are given to two decimal places, not four. How can the program be fixed to give answers formatted as from a cash register?

Perl has two answers to this problem: printf(format, number) and sprintf(format, number). Today, we’ll look at a few lines of code that show the use of these built-in functions:


#!/usr/bin/perl

print “Enter a number, please.”;
print “This program will round your number to two decimal places.”;
$num=<STDIN>;
$rounded=sprintf(“%.2f”,$num);
print “Using printf, your number, rounded to two decimal places, is “;
printf(“%.2f”,$num);
print “\n\nRecall: the number you entered is $num”;
print “\n\nFrom sprintf, rounded to two decimal places, “;
print “your number is $rounded”;

Let’s compare sprintf and printf. Both leave the input number unchanged. The function sprintf reformats it, and saves the reformatted number in a new variable. The function printf simply prints the number in the specified format.

I wish all of you the best of nights:)

Source:

McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Tagged with: , , ,

Leave a Reply