所以我知道有很多关于金钱和转换美分的问题。哎呀,我什至问了另一个问题,但我想提出一个稍微不同的问题,所以我希望那里没有重复的问题。
所以我创建了一个函数,它接受一个美元值并将其发送到 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 细节,我可以看到。
谁能帮助我进行这些调整?