problems with float conversion from a string
am 06.12.2007 16:02:37 von Remo
Hi everyone,
I'm a php newbie. I'm sorry for the trivial question:
If I have two string variables like:
$Media_A = "8.00"
$Media_B = "8.86"
and I try to use this statement in order to make a subtraction
like:
$Media_B - $Media_A, result is 0!
Why????
It's like two strings has been converted into integers.
I say that, why, if I set $Media_B="9.86", new result is 1.
This example uses strings because values coming from a table where
field are defined varchar(7).
Is there a way to cast those variables and calculate the correct
differences between those two variables values.
thanx for help
Remo
Re: problems with float conversion from a string
am 06.12.2007 16:27:16 von Joe Scylla
Remo wrote:
> Hi everyone,
> I'm a php newbie. I'm sorry for the trivial question:
>
> If I have two string variables like:
>
> $Media_A = "8.00"
> $Media_B = "8.86"
> and I try to use this statement in order to make a subtraction
> like:
> $Media_B - $Media_A, result is 0!
> Why????
>
> It's like two strings has been converted into integers.
> I say that, why, if I set $Media_B="9.86", new result is 1.
>
> This example uses strings because values coming from a table where
> field are defined varchar(7).
> Is there a way to cast those variables and calculate the correct
> differences between those two variables values.
>
> thanx for help
> Remo
You can cast a variable to a type by using:
$result = (float) $string;
See also here (chapter: Type Casting):
http://www.php.net/manual/en/language.types.type-juggling.ph p
Joe
Re: problems with float conversion from a string
am 06.12.2007 19:23:55 von ColdShine
Remo in
news:f247e715-3d72-4412-9483-1af84a6c6203@b15g2000hsa.google groups.com
wrote:
> If I have two string variables like:
>
> $Media_A = "8.00"
> $Media_B = "8.86"
> and I try to use this statement in order to make a subtraction
> like:
> $Media_B - $Media_A, result is 0!
> Why????
>
> It's like two strings has been converted into integers.
> I say that, why, if I set $Media_B="9.86", new result is 1.
PHP is type-juggling strings as integers. So, "8.00" (parsing stops at first
non-digit) is 8, as is "8.86". And 8-8 is... yes.
And this also explains the second example: "9.86" is 9.
--
ColdShine
"Experience is a hard teacher: she gives the test first, the lesson
afterwards." - Vernon Sanders law