I'll be obtaining jsvariable from on onclick javascript from the user. The user will input how much money they are spending in $xx.xx amount. It will come in, in string form. I need to do math on the amount, so I need it as a float.

I set it to a string as an example. I extract it from javascript into a php string variable:

<script> var jsvariable = "2.25"; </script> 

<?php $x = "<script>document.writeln(jsvariable);</script>";
 echo $x;  var_dump($x); ?>

The echo $x shows 2.25. The var_dump shows that $x is a string(38) "2.25 " So it's showing the $x variable now in php to be a 38 char string but it contains only 5 characters.

Then I try converting it with settype function. Also try re-casting it. It's not converting it.

<?php 
settype($x, "float"); 
echo "After settype x is "; echo $x; var_dump($x);

$y = (float)$x ; 
echo " y cast y is "; echo $y; var_dump ($y);
?>

After settype x is 0 float(0)

After casting y is 0 float(0)

How do I convert the $x string into a float number that's the right value of 2.25 ?

1

There are 1 answers

2
Felix G On

Just cast it like this: $y = (float)$x. You might want to check out type juggeling as well as String conversion to numbers.