Convert a string to a double - is this possible?

Php

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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

Solution 3 - Php

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

Solution 4 - Php

Why is floatval the best option for financial comparison data? bc functions only accurately turn strings into real numbers.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncsUView Question on Stackoverflow
Solution 1 - PhpFelix KlingView Answer on Stackoverflow
Solution 2 - PhpBrant MessengerView Answer on Stackoverflow
Solution 3 - PhpJSBձոգչView Answer on Stackoverflow
Solution 4 - PhpXenlandView Answer on Stackoverflow