0

Hi,

I'm having an trouble trying to printf the string.

<?php
$product_name = "pencils";
$product_price= 7.99;
printf( "Product %f will cost %1.1f dollars.",
$product_name, $product_price );
?>

The answer should look like this

Product pencils will cost $7.99 dollars

but instead it looks like this

Product 0.000000 will cost 8.0 dollars.

The printf (), sprintf(), fprintf(), is something I'm learning right now.

Is there a rule of thumb to understand how this works because the printf word confused me a lot, I can't seem to find a way to remember how each function works correctly without looking at the definition. It's been like a week now and I can't seem to write it correctly.

Any Suggestion or solution would be appreciated. Thanks.

2
Contributors
7
Replies
8
Views
5 Years
Discussion Span
Last Post by phorce
0

<?php
$product_name = "pencils";
$product_price= 7.99;
printf( "Product %f will cost %1.1f dollars.",
$product_name, $product_price );
?>

Can't you just echo it?

<?php
$product_name = (string) "pencils";
$product_price= 7.99;

echo "Product $product_name will cost $product_price";
?>
0

@phorce

Thanks for the reply! Thanks for the example, I will test it out.

0

@phorce

So in the future, I just used the word

(string)

instead of

printf (), sprintf(), fprintf(),

and used the "echo statement" print out the equation?

The "echo statement" works but it doesn't really help me answer my question regarding about printf (), sprintf(), fprintf()?

1

pencils

Here you go..

<?php
$product_name = "pencils";
$product_price= 7.99;
printf( "Product %s will cost %1.1f dollars.",
$product_name, $product_price );
?>

Remember, %s = string. %f = floating point number..

Hope this solves it :)

Votes + Comments
Thanks for the example and explanation!
0

@phorce

Thanks for the replying again! Thanks for the example and explanation. I will test it out.

2

@phorce

This the adjustments I made from your example:

<?php
$product_name = "pencils";
$product_price= 7.99;
printf( "Product %s will cost %1.2f dollars.",
$product_name, $product_price );
?>

and it print out:

Product pencils will cost $7.99 dollars !

It work! Thanks for the example and explanation! I appreciate you taking time to help me. Thanks!

Edited by LastMitch: grammer

0

No problem :)

Sorry if my answer was a little blunt last night; it was 3am!

Good luck with your project :)

P.S. Thres not a huge difference between echo/printf although I'm sure I read somewhere that echo is faster.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.