format.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * 金额格式化工具
  3. * 后端统一使用整型(分)存储金额,前端在此转换展示
  4. */
  5. /**
  6. * 分 → 元,保留2位小数
  7. * @param {number|null} cents 金额(分)
  8. * @returns {string|null} "12.50" 或 null
  9. */
  10. export function formatPrice(cents) {
  11. if (cents == null || cents === undefined) return null
  12. return (cents / 100).toFixed(2)
  13. }
  14. /**
  15. * 分 → 元,带 ¥ 前缀
  16. * @param {number|null} cents 金额(分)
  17. * @returns {string} "¥12.50" 或 "登录查看"
  18. */
  19. export function formatPriceWithSymbol(cents) {
  20. if (cents == null || cents === undefined) return '登录查看'
  21. return '¥' + (cents / 100).toFixed(2)
  22. }
  23. /**
  24. * 千分比 → 百分比字符串
  25. * @param {number|null} permillage 千分比(235 = 23.5%)
  26. * @returns {string} "23.5%" 或 "--"
  27. */
  28. export function formatRate(permillage) {
  29. if (permillage == null || permillage === undefined) return '--'
  30. return (permillage / 10) + '%'
  31. }
  32. /**
  33. * 百分制评分 → 展示值
  34. * @param {number|null} value 百分制(450 = 4.5分)
  35. * @param {number} fixed 小数位数
  36. * @returns {string} "4.5" 或 "--"
  37. */
  38. export function formatScore(value, fixed) {
  39. if (fixed === undefined) fixed = 1
  40. if (value == null || value === undefined) return '--'
  41. return (value / 100).toFixed(fixed)
  42. }