take the sprintf challenge

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

take the sprintf challenge

Post by neophyte »

Question one -- no clue how to make this work.
Integer or floating point with comma seperated thousands
1,200,300.00

Question 2 -- Add a dollar sign to the front of a number with two decimals. Here's what I'm working with:

Code: Select all

%01.2f
The end product should be $12.00

rules -- no string concatenation, or other functions, just sprintf().
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

If I'm barking up the wrong tree go ahead and say Yo! You can't do it with sprintf.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

I'm confused... is this just a puzzle? or are you actually looking for a solution?
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

I'm actually looking for a solution. The problem is that I need to be able to format numeric strings in specific ways that the client code specifies. I'm looking at sprintf but maybe I should be creating my own syntax...
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

if money_format() isn't general enough for you, have you considered preg_replace() ?

also check out number_format()
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

sprintf() won't handle thousands separation, but can do the basic money:

Code: Select all

[feyd@home]>php -r "printf('$%1.2f', 12.34);"
$12.34
[feyd@home]>php -r "printf('$%1.2f', 12.00);"
$12.00
[feyd@home]>php -r "printf('$%1.2f', 12);"
$12.00
[feyd@home]>php -r "printf('$%1.2f', 12.1);"
$12.10
[feyd@home]>php -r "printf('$%1.2f', .12);"
$0.12
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

Hmm thanks for the advice feyd.
Post Reply