Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to a double - is this possible?

Tags:

php

Just wondering in php, if it was possible to convert a string to a double. I am using a financial web service which provides a price as a string. I really need to process this as a double and was wondering how i would convert it

thanks

like image 582
csU Avatar asked Mar 29 '10 17:03

csU


People also ask

Can you convert a string to a double in C++?

C++ string to float and double Conversion The easiest way to convert a string to a floating-point number is by using these C++11 functions: std::stof() - convert string to float. std::stod() - convert string to double. std::stold() - convert string to long double .

How do you convert a string to a double in Python?

Use float() method or decimal() method to convert string to double in Python. Conversion of string to double is the same as the conversion of string to float.


2 Answers

Just use floatval().

E.g.:

$var = '122.34343'; $float_value_of_var = floatval($var); echo $float_value_of_var; // 122.34343 

And in case you wonder doubleval() is just an alias for floatval().

And as the other say, in a financial application, float values are critical as these are not precise enough. E.g. adding two floats could result in something like 12.30000000001 and this error could propagate.

like image 104
Felix Kling Avatar answered Oct 06 '22 08:10

Felix Kling


For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

$s = '1234.13'; $double = bcadd($s,'0',2); 

PHP: bcadd

like image 45
Brant Messenger Avatar answered Oct 06 '22 08:10

Brant Messenger