fmt()
For display — the display-safe version of calc with arithmetic, formatting, and error fallback.
fmt(value, options?)
fmt is the "display-safe" version of calc: same API, the first argument likewise supports arithmetic expressions, but the key difference is that errors fall back to _error instead of throwing — safe to use directly in template rendering, where a single bad value should never crash the whole page.
Use
fmt for display, calc for computation.fmt falls back on error (returns _error, default '-'); calc and all other functions (add/calcSum/chain…) throw on error — handle them with try/catch. Only fmt has a fallback.Signature
fmt(value: string | number | bigint, options?: IFmtOptions): string | number
interface IFmtOptions extends IFormat {
_error?: string | number // error fallback value (defaults to global _error, usually '-')
_precision?: number // division precision when used with arithmetic (defaults to global _precision)
_unit?: boolean // enable % unit mode (same as calc's _unit)
}
- Pass a
string⇒ evaluated as an arithmetic expression, then formatted (fmt('999.99 * 3')⇒'2999.97') - Pass a
number/bigint⇒ formatted directly - On error ⇒ returns the
_errorfallback (localoptions._errortakes priority over global; default'-')
For formatting fields see IFormat (e.g. { decimals: 2, thousands: true }). Returns string; returns number when { output: 'number' } is set.
Use Directly in Templates
<!-- A single bad value won't crash the page — automatically shows the '-' fallback -->
{{ fmt(`${price} * ${qty}`, { decimals: 2, thousands: true }) }}
Try It Live
fmt(1234567, { decimals: 2, thousands: true }) // "1,234,567.00"
fmt(1234567, { compact: 'zh' }) // "123.4567万"
fmt(0.5, { output: 'percent' }) // "50%"
fmt(0.5, { output: 'fraction' }) // "1/2"
在线运行⌘/Ctrl + Enter 运行
Usage
fmt(1234567) // "1234567"
fmt(1234567, { thousands: true }) // "1,234,567"
fmt(1234567, { decimals: 2, thousands: true }) // "1,234,567.00"
fmt(0.5, { output: 'percent' }) // "50%"
fmt(1234567, { compact: true }) // "1.23M"
fmt(1234567, { compact: 'zh' }) // "123.45万"
fmt(0.5, { output: 'fraction' }) // "1/2"
fmt(1000, { output: 'scientific' }) // "1e+3"
fmt(5, { pad: 3 }) // "005"
Output as number
Use { output: 'number' }:
fmt(0.1234, { decimals: 2, output: 'number' }) // 0.12 ← number type
For all formatting fields, see Number Formatting.