how to use PHP to convert numerical string to float?
Is there any php functions do this job? Or I should do this conversion myself? Further more, I will receive many strings like this, some are numerical and some are in scientific format, how can I convert all of them correctly without knowing the content?
Why do you need to do this? PHP understands scientific notation, so it will treat these as floats when you use them in mathmatical expressions.
I need to check if the float have less than 3 digital number, I write a function myself(expload the number by «.»), however when it meets mathmatical expression, it doesn’t work.
6 Answers 6
Try this example for converting your string var into float type:
Your best bet is to cast it.
$num = "1.0E+7"; $fl = floatval ($num); printf ("%.02f", $fl); // Result: 10000000.00
// type casting var_dump((float) "1.0E+7"); // float(10000000) // type juggling var_dump("1.0E+7" + 0.0); // float(10000000) // function var_dump(floatval("1.0E+7")); // float(10000000) // other stuff var_dump(round("1.0E+7")); // float(10000000) var_dump(floor("1.0E+7")); // float(10000000) var_dump(ceil("1.0E+7")); // float(10000000) var_dump(abs("1.0E+7")); // float(10000000) // weird var_dump(unserialize("d:"."1.0E+7".";")); // float(10000000) var_dump(json_decode('1.0E+7')); // float(10000000)
This question is in a collective: a subcommunity defined by tags with relevant content and experts.
PHP String to Float
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?
9 Answers 9
$rootbeer = (float) $InvoicedUnits;
Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.
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.
@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
float floatval ( mixed $var ) — Gets the float value of a string.
$string = '122.34343The'; $float = floatval($string); echo $float; // 122.34343
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 «,»
Well, if user write 1,00,000 then floatvar will show error. So —
floatval(preg_replace("/[^-0-9\.]/","",$input));
This is much more reliable.
$input = '1,03,24,23,434,500.6798633 this'; echo floatval(preg_replace("/[^-0-9\.]/","",$input));
Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2 :
But in Germany you would change comma and point:
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.
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.
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;
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
Use this function to cast a float value from any kind of text style:
function parseFloat($value) < return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,)([0-9-]))*$#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)
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 🙂
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.
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!).
PHP – How to convert string to float?
In this PHP tutorial, you shall learn how to convert a given string to a float value using typecasting or floatval() function, with example programs.
PHP – Convert string to float
To convert string to float in PHP, you can use Type Casting technique or PHP built-in function floatval().
In this tutorial, we will go through each of these methods and learn how to convert contents of a string to a float value.
Convert String to Float using Type Casting
To convert string to floating point number using Type Casting, provide the literal (float) along with parenthesis before the string literal. The expression returns float value of the string.
The syntax to type cast string to float number is
$float_value = (float) $string;
Example
In the following example, we will take a string with floating point number content, and convert the string into float using type casting.
PHP Program
Convert String to Float using floatval()
To convert string to float using PHP built-in function, floatval(), provide the string as argument to the function. The function will return the float value corresponding to the string content.
The syntax to use floatval() to convert string to float is
$float_value = floatval( $string );
Example
In the following example, we will take a string with float content, and convert the string into float value using floatval() function.
PHP Program
Conclusion
In this PHP Tutorial, we learned how to convert a string to float using typecasting and floatval() function.