搜尋

首頁  >  問答  >  主體

如何在 PHP 中複製 Excel FV 函數?

我正在將一些相當複雜的計算從 Excel 電子表格轉換為 PHP。我被困在 Excel 的 FV 函數的轉換上,它是這樣定義的:

FV( interest_rate, number_payments, payment, PV, Type )

我已經為此工作了 2 個小時,我肯定遺漏了一些東西。本質上,我需要將此功能複製到等效的 PHP 函數中,並採用上述所有參數。

任何幫助將非常感激。

P粉106301763P粉106301763387 天前849

全部回覆(1)我來回復

  • P粉621033928

    P粉6210339282023-11-05 00:04:08

    對 PHPExcel 函數函式庫稍作修改:

    /**
     * FV
     *
     * Returns the Future Value of a cash flow with constant payments and interest rate (annuities).
     *
     * @param   float   $rate   Interest rate per period
     * @param   int     $nper   Number of periods
     * @param   float   $pmt    Periodic payment (annuity)
     * @param   float   $pv     Present Value
     * @param   int     $type   Payment type: 0 = at the end of each period, 1 = at the beginning of each period
     * @return  float
     */
    function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) {
    
        // Validate parameters
        if ($type != 0 && $type != 1) {
            return False;
        }
    
        // Calculate
        if ($rate != 0.0) {
            return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
        } else {
            return -$pv - $pmt * $nper;
        }
    }   //  function FV()
    
    
    echo FV(0.0149562574418, 4, 43.875, -250);

    回傳 85.818510876629

    // 單元測試

    class ExcelTest extends \PHPUnit_Framework_TestCase
    {
    
        public function test_it_calculates_fv_value()
        {
            $test_data = [
                [ 0.005,          10, -200,  -500,    1,    2581.4033740601 ],
                [ 0.01,           12, -1000, null,    null, 12682.503013197 ],
                [ 0.009166666667, 35, -2000, null,    1,    82846.246372418 ],
                [ 0.005,          12, -100,  -1000,   1,    2301.4018303409 ],
                [ 0.004166666667, 60, -1000, null,    null, 68006.082841536 ],
                [ 0.025,          16, -2000, 0,       1,    39729.460894166 ],
                [ 0.0,            12, -100,  -100,    null, 1300            ]
            ];
    
            $test_case_id = 0;
            foreach($test_data as $test_case) {
                $test_case_id++;
                list($rate, $nper, $pmt, $pv, $type, $expected_result) = $test_case;
                $this->assertEquals($expected_result, Excel::FV($rate, $nper, $pmt, $pv, $type), "Test case $test_case_id failed", 0.0000001);
            }
        }
    
    }

    回覆
    0
  • 取消回覆