Doing exact real number arithmetic with PHP

自作多情 提交于 2019-12-18 04:17:17

问题


What is fastest and most easy way of making basic arithmetic operations on strings representing real numbers in PHP? I have a string representing MySQL's DECIMAL value on which I want to operate and return the result to a database after that. I would like to avoid errors introduced by floating-point real number representation.

Is there some standard library like Python's decimal? Are there any FOSS libraries you can recommend?

Regards


回答1:


You could use the BC math functions:

http://www.php.net/manual/en/ref.bc.php

Or the GMP functions, although they seem to be integer only.

http://www.php.net/manual/en/ref.gmp.php




回答2:


You can use the bc_math extension, which works exactly how you ask (it's used for arbitrary precision numbers):

$num = '123.456';
$twoNum = bcadd($num, $num);


来源:https://stackoverflow.com/questions/4502588/doing-exact-real-number-arithmetic-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!