Files
Neo-ZQYY/apps/DEMO-miniprogram/miniprogram/utils/format.wxs

84 lines
2.1 KiB
XML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// WXS 格式化工具 — WXML 中不能调用 JS 方法,需通过 WXS 桥接
// 规范docs/miniprogram-dev/design-system/DISPLAY-STANDARDS.md
/** 数字保留 N 位小数;空值返回 '--' */
function toFixed(num, digits) {
if (num === undefined || num === null) return '--'
return num.toFixed(digits)
}
/** 空值兜底null/undefined/'' 统一返回 '--' */
function safe(val) {
if (val === undefined || val === null || val === '') return '--'
return val
}
/**
* 金额格式化WXS 版)
* ¥12,680 / -¥368 / ¥0 / --
*/
function money(value) {
if (value === undefined || value === null) return '--'
if (value === 0) return '¥0'
var abs = Math.round(Math.abs(value))
var s = abs.toString()
var result = ''
var count = 0
for (var i = s.length - 1; i >= 0; i--) {
if (count > 0 && count % 3 === 0) result = ',' + result
result = s[i] + result
count++
}
return (value < 0 ? '-¥' : '¥') + result
}
/**
* WXS
* '--'1000
*/
function count(value, unit) {
if (value === undefined || value === null || value === 0) return '--'
var s = value.toString()
if (value >= 1000) {
var result = ''
var c = 0
for (var i = s.length - 1; i >= 0; i--) {
if (c > 0 && c % 3 === 0) result = ',' + result
result = s[i] + result
c++
}
return result + unit
}
return s + unit
}
/**
* 百分比展示WXS 版)
* 保留1位小数超过100%正常展示;空值返回 '--'
*/
function percent(value) {
if (value === undefined || value === null) return '--'
if (value === 0) return '0%'
return value.toFixed(1) + '%'
}
/**
* 课时格式化WXS 版)
* 整数 → Nh非整数 → N.Nh0 → 0h空 → --
*/
function hours(value) {
if (value === undefined || value === null) return '--'
if (value === 0) return '0h'
if (value % 1 === 0) return value + 'h'
return value.toFixed(1) + 'h'
}
module.exports = {
toFixed: toFixed,
safe: safe,
money: money,
count: count,
percent: percent,
hours: hours,
}