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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sprintf() not returning expected result

Status
Not open for further replies.

ppeel

Programmer
Dec 7, 2004
18
US
I have a variable $nfc_amt that I want to add leading zeroes to. The value of $nfc_amt is 115.
my code:
print "NFC_AMT before adding zeroes: $nfc_amt\n";
$nfc_amt = sprintf("%07d", $nfc_amt);
print "NFC_AMT after adding zeroes: $nfc_amt\n";

my result:

NFC_AMT before adding zeroes: 115
NFC_AMT after adding zeroes: 0000114

What am I doing wrong?

Thanks in advance for your help.
 
I imagine it's getting changed somewhere else. If I run the code you posted, I get the following results:
Code:
NFC_AMT before adding zeroes: 115
NFC_AMT after adding zeroes: 0000115
 
Another thought is, are you suing the sprintf statement to do rounding of a floating point number? That could be causing problems.
 
I actually retrieve this number from a DB2 table, and then try to add the leading zeroes.
When I changed the syntax to:
$nfc_amt = sprintf("%07.0f", $nfc_amt);
The Result is correct. So there is something in $nfc_amt that I'm not seeing.
This is a little disconcerting to me. I was comfortable using "%07d" and now I'm not sure it's always working. Out of a file of 6000 records, only 200 were returning the incorrect amount when using "%07d".
 
What is the data type of that field in your database? If you print everything without using printf/sprintf (so, just using print) are the values what you expect (without the leading zeros)?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top