本文目录导读:

针对PHP项目中数字迪拉姆(AED)与电子迪拉姆(eAED)的处理,以下是一些核心要点和代码示例:
货币表示基础
迪拉姆是阿联酋货币,通常保留2位小数,eAED是电子货币形式。
class CurrencyHandler {
// 货币格式化
public static function formatAED(float $amount, bool $includeSymbol = true): string {
$formatted = number_format($amount, 2, '.', ',');
return $includeSymbol ? "AED $formatted" : $formatted;
}
// 将eAED转换为数字(去除逗号等格式)
public static function parseEAED(string $eAmount): float {
// 移除货币符号、逗号等
$clean = preg_replace('/[^0-9.-]/', '', $eAmount);
return (float)$clean;
}
}
数据库存储设计
CREATE TABLE transactions (
id INT PRIMARY KEY AUTO_INCREMENT,
amount_cent BIGINT NOT NULL, -- 以分为单位存储避免浮点精度问题
currency_type ENUM('AED', 'eAED') NOT NULL,
exchange_rate DECIMAL(10, 6) DEFAULT 1.000000, -- AED转eAED汇率
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 视图:直接显示金额
CREATE VIEW transaction_view AS
SELECT
id,
amount_cent / 100 AS amount_decimal,
currency_type,
CASE
WHEN currency_type = 'eAED'
THEN amount_cent / 100 * exchange_rate
ELSE amount_cent / 100
END AS aed_equivalent
FROM transactions;
安全计算处理
class MoneyCalculator {
private const SCALE = 2;
// 使用bcmath进行精确计算
public static function add(string $amount1, string $amount2, int $scale = self::SCALE): string {
return bcadd($amount1, $amount2, $scale);
}
// AED与eAED转换
public static function convertToEAED(string $aedAmount, string $rate): string {
return bcmul($aedAmount, $rate, self::SCALE);
}
public static function convertFromEAED(string $eAmount, string $rate): string {
if (bccomp($rate, '0', 10) === 0) {
throw new InvalidArgumentException('汇率不能为0');
}
return bcdiv($eAmount, $rate, self::SCALE);
}
}
前端交互示例
// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$amount = filter_input(INPUT_POST, 'amount', FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION);
$currencyType = $_POST['currency_type'] ?? 'AED';
// 验证
if (!in_array($currencyType, ['AED', 'eAED'])) {
throw new InvalidArgumentException('无效的货币类型');
}
// 存储为分
$amountCent = (int) round($amount * 100);
// 如果是eAED,可能需要记录汇率
// insert into transactions (amount_cent, currency_type, exchange_rate) values ($amountCent, $currencyType, $rate)
}
显示与模板
// Twig模板示例
{{ transaction.amount|number_format(2, '.', ',') }} {{ transaction.currency_type }}
// 或使用自定义过滤器
{{ transaction.amount|format_aed }}
// 注册过滤器
$twig->addFilter(new \Twig\TwigFilter('format_aed', function($amount) {
return CurrencyHandler::formatAED($amount);
}));
注意事项
- 精度处理:始终使用整数(分/费尔)存储或
bcmath计算 - 汇率波动:eAED与AED的汇率可能变化,需记录交易时的汇率
- 验证规则:eAED通常允许更多小数位(如4位),AED通常2位
- 安全显示:敏感金额在前端显示前应经过格式化处理
// 验证金额格式
function validateAmount(string $amount, string $type): bool {
if ($type === 'AED') {
return preg_match('/^\d+(\.\d{1,2})?$/', $amount) === 1;
} elseif ($type === 'eAED') {
return preg_match('/^\d+(\.\d{1,4})?$/', $amount) === 1;
}
return false;
}
代码提供了PHP项目中处理数字迪拉姆和eAED的基础框架,可根据具体业务需求进行调整。