• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 rounding a decimal El Forum Guest   07-02-2007, 08:42 PM [eluser][email protected][/eluser] Is there any way i can round a decimal by just dropping off the last unecessary numbers wihtout rounding up or down??? ie. 3.459 to 3.45 or 5.999999 to 5.99 ???? El Forum Guest   07-02-2007, 10:41 PM [eluser]batteries[/eluser] The php manual hint hint .. but you don't wanna round, hmm. cast to string, and use string manipulation functions. El Forum Guest   07-02-2007, 11:20 PM [eluser][email protected][/eluser] Thanks. That's what I was thinking...but maybe there was a simpler way I didn't know about. El Forum Guest   07-02-2007, 11:28 PM [eluser]linuxbz[/eluser] How about this: Code:`\$x = floor(\$y*100)/100;` El Forum Guest   07-02-2007, 11:31 PM [eluser]Nanodeath[/eluser] I usually go with linuxbz's method. Just beware of the return types (round and floor both return a float for some reason). El Forum Guest   07-03-2007, 12:23 AM [eluser]linuxbz[/eluser] [quote author="Nanodeath" date="1183458693"]Just beware of the return types (round and floor both return a float for some reason).[/quote] Good point. Well, round() makes some sense because you can round it to a desired number of decimal places. The floor() function makes less sense, unless it is perhaps because you might want to floor() a larger number than the maximum integer size? I have heard that justification for a float before, though I can't think of an actual application of it. Actually, as often as this kind of situation comes up, an argument to floor() like the number of decimals to round() might be handy for some people. El Forum Guest   07-03-2007, 12:54 AM [eluser]batteries[/eluser] [quote author="linuxbz" date="1183458483"] Code:`\$x = floor(\$y*100)/100;`[/quote] Nice code. Tiny and very clever. El Forum Guest   07-03-2007, 06:32 AM [eluser]linuxbz[/eluser] @batteries - thanks. Also, to display 3.30 rather than 3.3 try this: Code:```\$y = 5.9999;  // number to round down \$p = 2;  // number of decimals \$n = pow(10,\$p);  // multiplier and divisor \$x = sprintf("#01.\${p}f", floor(\$y*\$n/\$n));  // result is a string``` which could be made into a function if needed more than once. Edit: replace the # with % in the sprintf function above ... forum software wouldn't allow a % there apparently.