# PHP and math

• Jul 22, 2000, 18:30
jumpthru
If you have two numbers and you divide them, how do you limit how many numbers go past the decimal. For example, if you devide 80 by 17 how do you get it to say 4.70 not 4.70588235294117647058823529411765. Thanks.

------------------
Nate - nate@jumpthru.com
ICQ 70944023
http://www.jumpthru.com - Unbelievable Website design!
http://www.jumpthru.com/christian - Learn, live, love, jesus christ...
• Jul 23, 2000, 05:16
\$my_sum = 80/17;
number_format(\$my_sum, X);

(Where X is an integer number of decimal places.)

or, if you need the "reduced" value elsewhere, you could put it in a new string.

\$my_sum = 80/17;
\$fixed_at_2dp= sprintf("%.2f",\$my_sum);

(The format identifiers are broadly the same as in C.)
• Jul 23, 2000, 05:37
ChrRmr
Assuming you want 4.71 which is the correct representation of 80/17 do:

\$number = 80/17;
\$number = sprintf ("%.2f", \$number);
echo \$number;

If (for some odd reason) you want 4.70, do:

\$number = 80/17;
\$number = explode(".",\$number);
\$number1 = \$number[0];
\$number2 = \$number[1];
\$number2 = substr(\$number2,0,2);

echo \$number1 .".". \$number2;

Christian
• Jul 23, 2000, 07:15
jumpthru
Lets say you divide 80 by 20 and get 4. By still doing the sprintf thingy, would it output 4.00?

------------------
Nate - nate@jumpthru.com
ICQ 70944023
http://www.jumpthru.com - Unbelievable Website design!
http://www.jumpthru.com/christian - Learn, live, love, jesus christ...
• Jul 23, 2000, 11:55
Kevin Yank
Talk about a FAQ and a half! :-)

There is no built-in method for adding decimal places "only when necessary", but using some regular expressions you can easily strip off unneeded ones afterwards. Here's a file that demonstrates the code:

&lt;!-- numtest.php --&gt;
&lt;HTML&gt;
&lt;BODY&gt;
&lt;?php
if (\$submit) {
\$n=number_format(\$n,2);
\$n = ereg_replace("0*\$","",\$n);
\$n = ereg_replace("\.\$","",\$n);

echo("&lt;P&gt;Result = \$n");
}
?&gt;
&lt;FORM ACTION=&lt;?=\$PHP_SELF?&gt; METHOD=POST&gt;
&lt;P&gt;Type a number to format:&lt;INPUT TYPE=TEXT NAME=n VALUE=&lt;?=\$n?&gt;&gt;
&lt;INPUT TYPE=SUBMIT NAME=submit&gt;
&lt;/FORM&gt;
&lt;/BODY&gt;
&lt;/HTML&gt;

------------------
-Kevin Yank.
http://www.SitePoint.com/
Helping Small Business Grow Online!

[This message has been edited by kyank (edited July 23, 2000).]
• Jul 23, 2000, 12:43
ChrRmr
\$number = 80/20;
\$number = sprintf ("%.2f", \$number);
echo \$number;

// output will be "4.00"

\$NUSER = 80/20;
\$number = sprintf ("%.2f", \$number);
echo \$number;

// output will be "0.00"

Christian

• Jul 24, 2000, 08:53
jumpthru
Thank you

------------------
Nate - nate@jumpthru.com
ICQ 70944023
http://www.jumpthru.com - Unbelievable Website design!
http://www.jumpthru.com/christian - Learn, live, love, jesus christ...