0

我有一个我自己无法解决的问题,我在想我可以被推到这里以获得在 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);
                    }
4

2 回答 2

1

您可以使用CAST()MySQL 的功能。

示例

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]
于 2013-01-22T16:05:03.650 回答
0

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

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

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

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

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

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

于 2020-11-28T18:55:09.413 回答