how do I do this with numbers in a string?

I have a Float say 25.4812756

When I dump it out, I want to limit my output to say, 25.48.  how can I limit the number of decimal places that get outputted into a string?

Thanks!
will1383Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Diablo84Connect With a Mentor Commented:
Use the round function, its what its designed for. printf is not needed here.

<?php
$var = 25.4812756;
echo round($var,2);
?>

http://us2.php.net/manual/en/function.round.php
0
 
BenMorelCommented:
Hello,

You should use printf (or sprintf in this example) for this purpose.

<?php
$float_number = 25.4812756;
$string = sprintf('%01.2f', $float_number);
echo $string; // 25.48
?>

See ya ;)
Ben
0
 
will1383Author Commented:
Oh yea,

Just like C.  Doh!
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
minichickenCommented:
Hi

You can also use number_format(); to do more formating to you output.

>>number_format ( float number, int decimals, string dec_point, string thousands_sep)
http://za2.php.net/number_format

e.g

$number = 1234.5678;

echo number_format($number, 2, '.', ',');

//outputs // 1,234.57

0
 
BenMorelCommented:
I agree Diablo ;)

The difference is that round($n,$max) outputs $n with $max MAXIMUM decimals.
printf() here has a fixed number of decimals, which is better for printing a price, for example.
Depends on what it is used for!

Ben
0
 
will1383Author Commented:
oh man.

sorry about pulling the trigger with the accepted answer.  I didn't realize there was this many ways to handle number formatting in php.  Thank you ALL!!!
0
 
BenMorelCommented:
No problem Will ;)
0
 
minichickenCommented:
No Prob...

I answered the question too slow anyways..... :)
0
All Courses

From novice to tech pro — start learning today.