Преобразование в и из CENTS - PullRequest
2 голосов
/ 10 июля 2011

Итак, я знаю, что было много вопросов относительно денег и конвертации в и из центов.Черт возьми, я даже задал другой, но я хочу задать немного другой вопрос, так что я надеюсь, что там нет дубликатов.

Итак, я создал функцию, которая принимает значение в долларах и отправляет его в CENTS.Но я думаю, что у меня есть небольшая проблема с моим кодом, и я надеюсь, что смогу немного его настроить.

$money4 = "10.0001";
// Converted to cents, as you can see it's slightly off. 
$money41 = "1001";
// So when "1001", get's put in the database, and then I return it back as a Money variable. 
// We get, "$10.01"... but what I have now is a leak in my amounts... as it rounded up to the second point. 

Итак, чтобы сделать то, что я сделал, я привык к функциям, которые я сделал, чтобы сделать это.

// This essentially gets a DOLLAR figure, or the CENT's Figure if requested.    
function stripMoney($value, $position = 0, $returnAs = "") 
{   
    // Does it even have a decimal?
    if(isset($value) && strstr($value, ".")) {

        // Strip out everything but numbers, decimals and negative
        $value    = preg_replace("/([^0-9\.\-])/i","",$value);
        $decimals = explode(".", $value);

        // Return Dollars as default
        return ($returnAs == "int" ? (int)$decimals[$position] : $decimals[$position]);

    } elseif(isset($value)) {
        // If no decimals, lets just return a solid number
        $value = preg_replace("/([^0-9\.\-])/i","",$value);
        return ($returnAs == "int" ? (int)$value : $value);
    }
}

Следующая функция, которую я использую, - это генерировать CENTS или возвращать ее обратно в долларах.

function convertCents($money, $cents = NULL, $toCents = TRUE)
{
    if(isset($money)) {
        if($toCents == TRUE) {
            // Convert dollars to cents
            $totalCents = $money * 100;
            // If we have any cents, lets add them on as well
            if(isset($cents)) {
                $centsCount = strlen($cents);
                // In case someone inputs, $1.1
                // We add a zero to the end of the var to make it accurate
                if($centsCount < 2) {
                    $cents = "{$cents}0";   
                }
                // Add the cents together
                $totalCents = $totalCents + $cents;
            }
            // Return total cents
            return $totalCents;

        } else {
            // Convert cents to dollars
            $totalDollars = $money / 100;
            return $totalDollars;
        }
    }
}

И последняя функция, которая собирает все вместе.Таким образом, мы просто используем 1 функцию, чтобы объединить 2 функции вместе в основном.

function convertMoney($value, $toCents = TRUE) {
    if(isset($value) && strstr($value, ".")) {
        return convertCents(stripMoney($value, 0), stripMoney($value, 1), $toCents);

    } elseif(!empty($value)) {
        return convertCents(stripMoney($value, 0), NULL, $toCents);
    }
}

То, что я сделал, может быть излишним, но я думаю, что это довольно солидно, кроме этой 1 детали, которую я вижу.

Кто-нибудь может мне помочь с этими настройками?

Ответы [ 2 ]

3 голосов
/ 10 июля 2011

Не используйте арифметику с плавающей запятой, если вам нужны точные ответы. Это относится практически ко всем языкам, а не только к PHP. Прочитайте большое предупреждение в руководстве по PHP .

Вместо этого проверьте BC Math или расширение GMP . Последний работает только с целыми числами, поэтому вас, вероятно, больше всего интересует математика до н.э.

2 голосов
/ 10 июля 2011

Я думаю money_format - это функция, которую вы искали ...

<?php

$number = 1234.56;

// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56

// Italian national format with 2 decimals`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// Eu 1.234,56

?>
...