format.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export function formatYuan(v) {
  2. if (v == null || v === '') return '0.00'
  3. const n = Number(v)
  4. if (Number.isNaN(n)) return '0.00'
  5. return n.toFixed(2)
  6. }
  7. export function formatFenAsYuan(fen) {
  8. if (fen == null || Number.isNaN(fen)) return '0.00'
  9. return (fen / 100).toFixed(2)
  10. }
  11. /**
  12. * 计量 + 单位 +(规格),如 500 克(礼盒装);无规格时不显示括号
  13. */
  14. export function formatMeasureUnitSpec(measureValue, unitName, spec) {
  15. const unitText = (unitName || '').trim()
  16. const specText = spec != null ? String(spec).trim() : ''
  17. let base = ''
  18. if (measureValue != null && measureValue !== '') {
  19. const num = Number(measureValue)
  20. if (!Number.isNaN(num)) {
  21. const measureText = String(num).replace(/\.?0+$/, '')
  22. base = unitText ? `${measureText} ${unitText}` : measureText
  23. } else {
  24. const measureText = String(measureValue).trim()
  25. base = unitText ? `${measureText} ${unitText}` : measureText
  26. }
  27. } else if (unitText) {
  28. base = unitText
  29. } else if (!specText) {
  30. return '-'
  31. }
  32. if (specText) {
  33. return base ? `${base}(${specText})` : `(${specText})`
  34. }
  35. return base || '-'
  36. }
  37. /** 数量 × 计量单位(规格),如 10×500 克(礼盒装) */
  38. export function formatQtyMeasureUnitSpec(qty, measureValue, unitName, spec) {
  39. const inner = formatMeasureUnitSpec(measureValue, unitName, spec)
  40. if (inner === '-') return String(qty)
  41. return `${qty}×${inner}`
  42. }