views:

18101

answers:

4

I am not familiar with PHP at all and had a quick question.

I have 2 variables @pricePerUnit and @invoicedUnits. Here's the code that is setting these to values:

$InvoicedUnits = ((string) $InvoiceLineItem->InvoicedUnits);
$pricePerUnit = ((string) $InvoiceLineItem->PricePerUnit);

If I output this, I get the correct values. Lets say 5000 invoiced units and 1.00 for price.

Now, I need to show the total amount spent. When I multiply these two together it doesn't work (as expected, these are strings).

But I have no clue how to parse/cast/convert variables in PHP.

What should I do?

+11  A: 
$rootbeerFloat = (float) $InvoicedUnits;

Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.

Jonathan Sampson
Its the most simple method.. but occasionally I have run into issues doing this with certain database configs and `VARCHAR>11` in length.. haven't narrowed down exactly why yet.
Talvi Watia
+2  A: 

You want the floatval function http://us3.php.net/manual/en/function.floatval.php:

float floatval  ( mixed $var  ) - Gets the float value of a string.

<?php
 $var = '122.34343The';
 $float_value_of_var = floatval($var);
 echo $float_value_of_var; // 122.34343
?>
earino
+1  A: 

Well, if user write 1,00,000 then floatvar will show error. So -

floatval(ereg_replace("[^-0-9\.]","",$input));

This is much more reliable.

Usage :

$input = '1,03,24,23,434,500.6798633 this';
echo floatval(ereg_replace("[^-0-9\.]","",$input));
HADI
+1  A: 

Dealing with markup in floats is a non trivial task. In the english/american notation you format one thousand plus 46*10-2:

1,000.46

But in germany you would change comma and point:

1.000,46


This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measure of the Zend Framework for this task. This component will parse the string to a float by the users language.

Tobias P.