繁体   English   中英

php和mysql中增值税的十进制精度

[英]decimal precision for vat taxes in php and mysql

我有一个我自己无法解决的问题,我想我可以被推到这里以获得最佳精度计算 php 和 mysql 中的增值税价格。

例如:

I have the gross price = 1199
The TAX Amount is      = 24
to extract the vat     = 1199 / 1.24 = 966.93548387096 round(966.93548387096,2) = 966.94
ok
now this value will be saved in mysql with decimal 12,2

Now, if you add the vat = 966.94 * 24 / 100 = 232.0656 round(232.0656,2) = 232.07
Final                   = 966.94 + 232.07 = 1199.01

我的问题是,如何在不浮动的情况下获得 1199?

任何帮助都值得赞赏。!

更新:

数据库中保存的值为 966.94,其中应用增值税金额。

当我在数据库中引入价格时,一个选项可以是用 4 位小数保存值,但为此我需要覆盖一个数组以提取列并取出增值税。

像:

$arrResult = array();
            $handle = fopen("uploads/csv/".$csv, "r");
            if( $handle ) {
            while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $arrResult[] = $row;
            }
            fclose($handle);
            }
            $titles = array_shift($arrResult);
            // need to take out the price and apply price / 1.24 and save the value as 4 decimal in mysql
            $keys = array('code', 'price');

            $final = array();

                    foreach ( $arrResult as $key => $value ) {
                                $final[] = array_combine($keys, $value);
                    }

您可以使用 MySQL 的CAST()函数。

示例

mysql> select 1199.01 as floating, cast( 1199.01 as signed ) as non_floating;
+----------+--------------+
| floating | non_floating |
+----------+--------------+
|  1199.01 |         1199 |
+----------+--------------+
1 row in set (0.00 sec)

参考
MySQL 中的类型转换

CAST can be used to convert to the following types:

 1. BINARY[(N)]
 2. CHAR[(N)] DATE
 3. DATETIME DECI
 4. MAL[(M[,D])]
 5. SIGNED [INTEGER]
 6. TIME
 7. UNSIGNED [INTEGER]

这是一个老问题,但您永远不应该使用浮点数来表示货币金额。

这是因为浮点数在计算上造成了很多麻烦(如果您在网上搜索,您会发现大量解释此问题的文章)。

因此,解决方案是使用像https://github.com/moneyphp/money这样的值对象

然后,您将在数据库中保存基本金额,即最小单位的简单整数。

这意味着 100,00 欧元表示为10000美分。

仅对整数进行操作(并在内部使用字符串)这个库非常非常精确!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM