Convert a string to a double - is this possible?

前端 未结 4 1604
既然无缘
既然无缘 2020-12-03 04:29

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 th

相关标签:
4条回答
  • 2020-12-03 04:45

    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.

    0 讨论(0)
  • 2020-12-03 04:49

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

    0 讨论(0)
  • 2020-12-03 04:52

    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

    0 讨论(0)
  • 2020-12-03 05:00

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

    0 讨论(0)
提交回复
热议问题