PHP中的MySQL DECIMAL处理 [英] MySQL DECIMAL handling in PHP

查看:88
本文介绍了PHP中的MySQL DECIMAL处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如通常讨论的那样(例如,在在MySQL中存储0.00001 ),DECIMAL数据类型应用于需要准确性/正确性的字段,例如帐户余额.

As commonly discussed, (for example here Storing 0.00001 in MySQL ) the DECIMAL data-type should be used for fields where precision / correctness is required, such as an account balance.

但是,我想知道PHP如何处理这些值,如果它们在内部以浮点数进行处理,那么从数据库读取这些值,进行一些计算并再次写回它们时是否仍然存在问题.如果是这样,我们如何强制PHP保持精确度?

I was wondering however, how PHP handles these values and, if they are internally handled as floats, if there is still a problem when reading these values from the database, doing some calculations and writing them back again. If so, how can we force PHP to keep precision in tact?

推荐答案

该变量最初可能是PHP中的字符串(从MySQL结果对象读取时).通常,不能依靠PHP的浮点数据类型来保持所需的精确十进制值.您应该使用任意精度的数学库,例如 GMP .(当您获取结果对象的一行时,将 DECIMAL 列值传递给适当的构造函数,然后使用所使用的库提供的函数对其进行操作.)

The variable is probably a string initially in PHP (when read from the MySQL result object). In general, PHP's floating-point datatype cannot be relied upon to keep the precise decimal value required. You should use an arbitrary-precision mathematics library like GMP. (When you fetch a row of the result object, pass the DECIMAL column value in to the appropriate constructor, and then operate on it using the functions provided by the library you are using.)

要更深入:假设您有一个存储在数据库中的金额,位于 DECIMAL(6,4)列中.您想将其提取到PHP中,以对其进行处理.您发出查询以获取该列.您将查询的第一行提取到关联数组中.假设该行的值为 2.5674 .您的数组现在类似于 array('MyDecimal'=>'2.5674')(数字显示为字符串).您(据我所知)使用 gmp_init()将该字符串转换为GMP资源.现在,您可以使用其他GMP功能使用该数字进行数学运算.如果要存储GMP编号,则可以使用 gmp_strval()将其转换回字符串(如果您正在使用可以处理GMP资源的数据库抽象层,则不必这样做)

To go more into depth: Suppose you have an amount stored in the database, in a DECIMAL(6, 4) column. You want to fetch that into PHP, to do something with it. You issue a query to fetch that column. You fetch the first row of the query into an associative array. Suppose that the value from that row is 2.5674. Your array is now something like array('MyDecimal' => '2.5674') (the number appears as a string). You use (as far as I can tell) gmp_init() to convert that string to a GMP resource. Now you can do mathematics with that number using the other GMP functions. If you want to store a GMP number, you could convert it back to string using gmp_strval() (perhaps you do not have to do this if you are using a database abstraction layer that can handle GMP resources).

这篇关于PHP中的MySQL DECIMAL处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆