Member Avatar for LastMitch

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.

<?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";
?>
Member Avatar for LastMitch

@phorce

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

Member Avatar for LastMitch

@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()?

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 :)

commented: Thanks for the example and explanation! +0
Member Avatar for LastMitch

@phorce

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

Member Avatar for LastMitch

@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!

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.