Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sprintf Question

Status
Not open for further replies.

BStopp

Programmer
Dec 29, 2003
29
US
According to my books.. if you put a number in your format it makes the result that many characters as a minimum. When dealing with floating point numbers, does the decimal count as one of those characters?

Example:
$number = sprintf("%05.1f", 0)

This results in 000.0
Technically it's 5 characters, but when dealing with numbers, i've never heard of the decimal counting in the minimum field width.

In order to get this: 0000.0
my code would have to be

$number = sprintf("%06.1f", 0)

Correct?

B Stopp
 
Certainly seems to be the case...

Code:
#!/usr/bin/perl

@numbers = qw(176.4 22.1 998.54 33.34 21 17.4 1.6);

foreach $number (@numbers) {
  $formatted = sprintf("%06.1f", $number);
  print "$number -> $formatted\n";
}

gives output:-

Code:
[blue]176.4 -> 0176.4
22.1 -> 0022.1
998.54 -> 0998.5
33.34 -> 0033.3
21 -> 0021.0
17.4 -> 0017.4
1.6 -> 0001.6[/blue]


Kind Regards
Duncan
 
just to check this was not a perl peculiarity, i tried gcc on a few samples. Same as duncdude
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top