# converting to 2 decimal places in php

Printable View

• Jan 10, 2001, 08:38
backpacklondon.com
Hello again,

Another quickie....

How do I convert a number with many decimal places, to just 2 decimal places please (i.e. like with prices)?

e.g. \$total = 1.222222;

so how would I make \$total = 1.22

Thanks,

Jason
• Jan 10, 2001, 08:51
insomniac
Hi Jason,

I had (almost) the same problem. This thread may be able to help you out:

http://www.sitepointforums.com/showt...threadid=13628

Andrew.
http://www.mammoth.com.au/
• Jan 10, 2001, 09:35
backpacklondon.com

hmmmmm not quite,

Thanks insomniac, but I think this will remove all decimal places!!!

I'd like to keep 2 of them, e.g. £14.33

So any other ideas please?

Regards,

Jason
• Jan 10, 2001, 09:43
insomniac
Jason,

I know that if you play around with that code in the other thread, you can get the result your looking for.

Andrew.
http://www.mammoth.com.au/
• Jan 10, 2001, 10:13
Karl
\$var = sprintf( "%.2f", \$var );

Should return \$var to 2 decimal places.
• Jan 10, 2001, 10:25
PeterW
perhaps

\$value = 14.8366723786;
// change to whatever value...

\$value = \$value * pow(10, 3);

\$value = floor(\$value);

\$value = (float) \$value/10;
(float) \$modSquad = (\$value - floor(\$value));
\$value = floor(\$value);
if (\$modSquad > .5){
\$value++;
}

\$value = \$value / (pow(10, 2));

okay.. I was beaten to it.. and my way is sooooooo complicated but never mind ;)

<Edited by PeterW on 01-10-2001 at 11:28 AM>
• Jan 10, 2001, 10:41
backpacklondon.com
thanks guys!!!
• Jan 10, 2001, 10:45
freddydoesphp
There is a function in php for this

\$var = number_format(\$var, 2);

where number_format converts the given string to the number of decimal point specified, in this case 2