Global Config

setConfig / resetConfig — global error fallback / default format / precision.

Global Config

import { getConfig, resetConfig, setConfig } from '@wzo/calc'

interface IGlobalConfig {
    _error: string | number // fmt error fallback value, default '-' (only used by fmt; calc etc. throw on error)
    _fmt?: IFormat // global default format (IFormat object), none by default
    _compact_default: string // default compact preset, default ''
    _precision: number // division precision, default 50
}

Usage

// fmt returns 0 instead of '-' on error (_error only affects fmt)
setConfig({ _error: 0 })
fmt('a + b') // 0 (b is undefined)

// global default: 2 decimal places + thousands separator
setConfig({ _fmt: { decimals: 2, thousands: true } })
calc('1000 + 234') // "1,234.00"

// increase division precision
setConfig({ _precision: 100 })
divStr('1', '3') // 0.333... to 100 digits

// reset everything
resetConfig()

Try It Live

Remember to call resetConfig() after changing the global config, otherwise it will affect other Playgrounds on this page.

setConfig({ _fmt: { decimals: 2, thousands: true } })
calc('1000 + 234') // "1,234.00"
resetConfig()
在线运行⌘/Ctrl + Enter 运行

Per-call Override

Local options take priority over global config — override a single call without touching globals:

  • fmt's _error, calc / fmt's _fmt / _precision
  • Division / average: div / divStr / chainDiv / calcAvg accept { _precision } as a trailing argument to override precision for that call only (no global side effects)
setConfig({ _error: '-' })
fmt('1/0') // "-"
fmt('1/0', { _error: 'ERR' }) // "ERR"  ← per-call override

// division / average: trailing { _precision } sets precision for that call only
divStr('100', '3', { _precision: 5 }) // "33.33333"
div(100, 3, { _precision: 2 }) // 33.33
calcAvg([10, 20, 25], { _precision: 2 }) // "18.33"
chainDiv(100, 3, { _precision: 5 })() // "33.33333"  ← precision applies to the whole chain's division

App-wide Config (setConfig)

Apply a single config for your entire application — call it once, as early as possible in your entry point (main.ts):

main.ts
import { setConfig } from '@wzo/calc'
setConfig({ _error: 0, _fmt: { decimals: 2, thousands: true } })

After that, any import { fmt } from '@wzo/calc' anywhere in the app will use this config.

setConfig is a global singleton: it must run before any calc / fmt call, otherwise that call will use the default values. If you only need to override precision for a single division or average, use the per-call { _precision } approach described above — there is no need to modify the global config.