price.helpers.js 1.01 KB
/**
 * @file 众筹分包金额格式化纯函数
 * 算法与 balanceNote/index.wxs `priceFilter`(分→元)保持一致;修改须同步 wxs 与 tests/wxsFilters.test.mjs
 */

/**
 * 分转元,保留两位小数
 * @param {number} cents 金额(分)
 * @returns {string}
 */
export function centsToYuan(cents) {
  const pow = Math.pow(10, 2)
  return (Math.round((cents / 100) * pow) / pow).toFixed(2)
}

/**
 * 元金额格式化,保留两位小数(调用方已除 100 时使用)
 * @param {number} yuan 金额(元)
 * @returns {string}
 */
export function formatYuan(yuan) {
  const pow = Math.pow(10, 2)
  return (Math.round(yuan * pow) / pow).toFixed(2)
}

/**
 * 带 ¥ 前缀的展示金额
 * @param {number} amount
 * @param {{ inputUnit?: 'yuan'|'cents' }} [options]
 * @returns {string}
 */
export function formatPriceDisplay(amount, options = {}) {
  const { inputUnit = 'yuan' } = options
  const formatted = inputUnit === 'cents' ? centsToYuan(amount) : formatYuan(amount)
  return `¥${formatted}`
}