Forum Moderators: coopster

Message Too Old, No Replies

Recast a float into a percentage

can it be done?

         

neophyte

8:48 am on Mar 24, 2006 (gmt 0)

10+ Year Member



I'm drawing a number from a field in a table. the field has a datatype of float(3,2). This field holds a representation for a percentage. Viewing the applicatios back end, a visual representation of 12.00 (indicated as a percent) is fine. But on the front end of this app, this number must be used in a calculation.

There's my problem - recasting this number from a float to a percentage representation (12.00 to 0.12) for use in the calculation.

I've looked at number_format in php and all over the mysql manual but can't find anything that will allow me to either re-define the table field as a regular percent (which at this point I'm willing to do) or re-cast the number in a 0.xx format when it's loaded into a variable for a calculation.

What's the best way to do this?

Thanks to all in advance,

Neophyte

omoutop

10:34 am on Mar 24, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



$foo = 12.50; // float
$foo = $foo/100;
$bar = (float) $foo; // cast to float according to manual... check [gr2.php.net...]

gettype() will define $bar as double! manual states that this must be a float.. strange!

echo "\$bar==$bar; type is " . gettype ($bar) . "<br />\n";

Not much of a help but was all i got from manual

coopster

2:50 pm on Mar 24, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I never use gettype() [php.net], you are better off using the
is_*
functions (see manual page for details). Or better yet, if you are just checking to see what a variable has been cast as use var_dump [php.net]. Also, as stated in the manual page:

(for historical reasons "double" is returned in case of a float, and not simply "float")

Just something that may help in the future.

Back to topic --

12.00 or 0.12 are both float values. PHP is going to use float types during numeric operations in this instance. To get the value from the database in a percentage value for use in numeric operations you can either have it returned already for you or you can convert in your PHP calcs:

-- 
-- SQL query that will convert 12.00 to 0.12:
--
SELECT float_field/100 AS percentage FROM table
--
-- or, using PHP:
--
$percentage = $row['floatfield']/100;

neophyte

2:00 am on Mar 25, 2006 (gmt 0)

10+ Year Member



omoutop and coopster -

Thanks HUGE to you both. Yeah, (duhhh!) float/100! God! Basic, basic, so basic. Thanks to you both for being a seeing-eye-dog for the mathmatically blind!

This is what happens when a graphic designer decides to become a programmer!

Thanks again!

Neophyte