151

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?

Nik
  • 2,885
  • 2
  • 25
  • 25

9 Answers9

261
$rootbeer = (float) $InvoicedUnits;

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

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 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 Jul 03 '10 at 20:09
  • 4
    ^worth noting that (float) removes 0 from string if it's the first digit –  Jan 24 '17 at 12:47
  • 5
    Also note that "11,000.00" will output 11 instead of the expected 11000.00 – CodeJunkie Oct 07 '19 at 16:04
  • @CodeJunkie, how to fix that? I need to convert a string to float but I keep losing my zeros – answerSeeker Aug 22 '22 at 23:00
  • @answerSeeker It's not possible to append zeros to the end of a number... If you must have the zeros then keep it a string or store as a float and format it when you want to display it. The concept is called padding, number_format() should do the trick – CodeJunkie Sep 08 '22 at 22:39
  • @CodeJunkie I fixed it with something like `$content= number_format((float)str_replace('$', '', $content), 2, '.', ''); ` – answerSeeker Sep 10 '22 at 00:22
94

You want the non-locale-aware floatval function:

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

Example:

$string = '122.34343The';
$float  = floatval($string);
echo $float; // 122.34343
hakre
  • 193,403
  • 52
  • 435
  • 836
earino
  • 2,885
  • 21
  • 20
  • 9
    kudos for mentioning the locale-awareness. I just spent 1,5h tracking down an issue caused by different locales causing `(float)` to convert on the first server to "," and on the second to "," – Dr. Gianluigi Zane Zanettini Jan 22 '16 at 15:36
29

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

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

This is much more reliable.

Usage :

$input = '1,03,24,23,434,500.6798633 this';
echo floatval(preg_replace("/[^-0-9\.]/","",$input));
Brad Koch
  • 19,267
  • 19
  • 110
  • 137
HADI
  • 2,829
  • 1
  • 26
  • 26
10

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.

Nik
  • 2,885
  • 2
  • 25
  • 25
Tobias P.
  • 4,537
  • 2
  • 29
  • 36
  • 3
    Nowadays (+3 years), one could use [NumberFormatter](http://php.net/NumberFormatter.parse) as of PHP 5.3 with the `intl` extension. – zamnuts Nov 16 '13 at 06:22
  • 1
    PHP 5.3 had been available when i answered the question, but until your comment i was not aware of this single function as there are dozens of libraries doing something similar. But they won't have such a good coverage of locales as the intl extension has. Thanks, i'll try to remember it. – Tobias P. Nov 19 '13 at 20:33
4

you can follow this link to know more about How to convert a string/number into number/float/decimal in PHP. HERE IS WHAT THIS LINK SAYS...

Method 1: Using number_format() Function. The number_format() function is used to convert a string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.

$num = "1000.314"; 

//Convert string in number using  
//number_format(), function 
echo number_format($num), "\n"; 

//Convert string in number using  
//number_format(), function 
echo number_format($num, 2); 

Method 2: Using type casting: Typecasting can directly convert a string into a float, double, or integer primitive type. This is the best way to convert a string into a number without any function.

// Number in string format 
$num = "1000.314"; 

// Type cast using int 
echo (int)$num, "\n"; 

// Type cast using float 
echo (float)$num, "\n"; 

// Type cast using double 
echo (double)$num; 

Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.

// Number in string format 
$num = "1000.314"; 

// intval() function to convert  
// string into integer 
echo intval($num), "\n"; 

// floatval() function to convert 
// string to float 
echo floatval($num); 

Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.

// Number into string format 
$num = "1000.314"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0, "\n"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0.0, "\n"; 

// Performing mathematical operation  
// to implicitly type conversion 
echo $num + 0.1;
Manoj
  • 1,530
  • 2
  • 13
  • 18
  • 2
    Adding the output that would be received in each of those cases as a comment would help a ton without us having to test out each scenario – Uriahs Victor Sep 11 '20 at 11:42
1

Use this function to cast a float value from any kind of text style:

function parseFloat($value) {
    return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}

This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values. You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)

Hafenkranich
  • 1,696
  • 18
  • 32
  • any comments on why this is bad / where does it fail? – Hafenkranich Apr 28 '17 at 09:16
  • or is there a likewise flexible way which is faster? – Hafenkranich Jun 30 '17 at 11:07
  • 1
    It uses the e flag, which is "no longer supported". That's my guess. – Leif Oct 06 '17 at 10:18
  • I wonder if using the `filter_var()` functions wouldn't be faster (while still handling the issue you mention about different locales). `preg_replace()` in PHP is not too bad in terms of speed, but my guess would be that `filter_var()` is a stub to a library function written in C. However, to be sure, the only way to know is to put both solutions through a benchmark and compare the results :-) – Gwyneth Llewelyn Jul 28 '22 at 19:55
0

I was running in to a problem with the standard way to do this:

$string = "one";

$float = (float)$string;

echo $float; : ( Prints 0 )

If there isn't a valid number, the parser shouldn't return a number, it should throw an error. (This is a condition I'm trying to catch in my code, YMMV)

To fix this I have done the following:

$string = "one";

$float = is_numeric($string) ? (float)$string : null;

echo $float; : ( Prints nothing )

Then before further processing the conversion, I can check and return an error if there wasn't a valid parse of the string.

Morris Buel
  • 126
  • 1
  • 8
0

If you need to handle values that cannot be converted separately, you can use this method:

try {
    // use + 0 if you are accounting in cents 
    $doubleValue = trim($stringThatMightBeNumeric) + 0.0;
} catch (\Throwable $th) {
    // bail here if you need to
}
Jannie Theunissen
  • 28,256
  • 21
  • 100
  • 127
0

For the sake of completeness, although this question is ancient, it's worth mentioning the filter_var() set of functions, which should not only handle the formatting bits itself, but also validate or sanitise the output, thus being safer to use in the context of a form being filled in by users (or, eventually, a database that might have some corrupted/inconsistent fields):

$InvoicedUnits = (float) filter_var($InvoiceLineItem->InvoicedUnits,
  FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$pricePerUnit  = (float) filter_var($InvoiceLineItem->PricePerUnit,
  FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));

printf("The total is: %.2f\n", $InvoicedUnits * $pricePerUnit); // both are now floats and the result is a float, formatted to two digits after the decimal sign.

This sanitises the output (which will still remain a string) and will accept the current locale's setting of the decimal separator (e.g. dot vs. comma); also, there are more options on the PHP manual for validation (which will automatically convert the result to a float if valid). The results will be slightly different for different scenarios — e.g. if you know in advance that the $InvoiceLineItem will only have valid digits and symbols for floating-point numbers, or if you need to 'clean up' the field first, getting rid of whitespace, stray characters (such as currency symbols!), and so forth.

Finally, if you wish to have nicely-formatted output — since the total is expressed in a currency — you should also take a look at the built-in NumberFormatter class, and do something like:

$InvoicedUnits = (float) filter_var($InvoiceLineItem->InvoicedUnits,
  FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
$pricePerUnit  = (float) filter_var($InvoiceLineItem->PricePerUnit,
  FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));

$fmt = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo 'Total is: ' . $fmt->formatCurrency($InvoicedUnits * $pricePerUnit, 'EUR') . PHP_EOL;

This will also handle thousand separators (spaces, dots, commas...) according to the configured locale, and other similar fancy things.

Also, if you wish, you can use '' (the empty string) for the default locale string (set either by the server or optionally by the browser) and $fmt->getSymbol(NumberFormatter::INTL_CURRENCY_SYMBOL) to get the default 3-letter currency code (which might not be what you want, since usually prices are given in a specific currency — these functions do not take currency exchange rates into account!).

Gwyneth Llewelyn
  • 796
  • 1
  • 11
  • 27