Files

23 lines
980 B
JavaScript

/* The same rule as money.py: 4 decimal places, round each line half up to cents. */
(function (root) {
function units(value) {
const s = String(value || '0').trim();
if (!/^\d+(\.\d{0,4})?$/.test(s)) throw new Error('数量和单价须为非负数字,最多四位小数');
const parts = s.split('.');
const n = BigInt(parts[0]) * 10000n + BigInt((parts[1] || '').padEnd(4, '0'));
if (n > 9999999990000n) throw new Error('数量或单价过大');
return n;
}
function lineCents(qty, price) {
const cents = (units(qty) * units(price) + 500000n) / 1000000n;
if (cents > 99999999999999n) throw new Error('金额过大');
return cents;
}
function format(cents) {
return (cents / 100n).toString() + '.' + (cents % 100n).toString().padStart(2, '0');
}
const api = {units, lineCents, format};
if (typeof module !== 'undefined') module.exports = api;
root.POMoney = api;
})(typeof window === 'undefined' ? globalThis : window);