php 将字符串转换为双精度值 - 这可能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2540078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a string to a double - is this possible?
提问by csU
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
只是想知道在 php 中,是否可以将字符串转换为双精度值。我正在使用提供价格作为字符串的金融网络服务。我真的需要把它作为一个双重处理,并想知道我将如何转换它
thanks
谢谢
回答by Felix Kling
Just use floatval().
只需使用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().
如果您想知道doubleval()它只是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.30000000001and this error could propagate.
另一种说法是,在金融应用程序中,浮点值至关重要,因为它们不够精确。例如,添加两个浮点数可能会导致类似的结果,12.30000000001并且此错误可能会传播。
回答by Brant Messenger
For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.
对于任意精度数学,PHP 提供了二进制计算器,它支持任何大小和精度的数字,表示为字符串。
$s = '1234.13';
$double = bcadd($s,'0',2);
回答by JSB????
Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input verycarefully.
使用doubleval(). 但是在金融交易中使用小数时要非常小心,并非常仔细地验证用户输入。
回答by Xenland
Why is floatval the best option for financial comparison data? bc functions only accurately turn strings into real numbers.
为什么 floatval 是财务比较数据的最佳选择?bc 函数只能准确地将字符串转换为实数。
回答by Dziamid Harbatsevich
Here is comparisonof floatval()and bcadd()to turn string to double/float.
下面是比较的floatval()和bcadd()把串到双/浮动。
MONITOR:
监视器:
$VAR for test - 61538.18
floatval() --- 61538.18
var_dump(floatval()) --- float(61538.18)
bcadd() --- 61538.18
var_dump(bcadd()) --- string(8) "61538.18"
CODE:
代码:
$var="61538.18";
echo "<p>$VAR for test - " . $var . "</p>";
$float_value_of_var = floatval($var);
echo "<p>floatval() --- " . $float_value_of_var . "<br>var_dump(floatval()) --- ";
var_dump($float_value_of_var);
echo "</p>";
$bcad = bcadd($var,'0',2);
echo "<p>bcadd() --- " . $bcad . "<br>var_dump(bcadd()) --- ";
var_dump($bcad);
**P.S.: ***Use Filters for good ;) !*
**PS: *** 永远使用过滤器 ;) !*
//-- Example with filters for floatval()
$var = floatval(filter_var($var, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
floatval($var);
var_dump($var);

