const groupRegex = /(\d)(?=(\d{3})+\.)/g
constructor(private readonly setting: CurrencySetting) {
* @param precision 小数点后精确位数(不传递则使用配置)
* @returns {string} 格式化后的 价格
* 例如 -1111.2 => -$1,111.2
format(value: number, precision?: number): string {
precision = this.normalizePrecision(precision)
value = this.parse(value)
const isNegative = value < 0
let formatted = this.toFixed(value, precision).replace(groupRegex, '$1' + this.setting.group)
// 如果当前的 小数点符号 不是 '.', 就进行修改
if (this.setting.decimal !== '.') {
formatted = formatted.substring(0, formatted.length - precision - 1) + this.setting.decimal + formatted.substring(formatted.length - precision)
return (isNegative ? '-' : '') + (this.setting.symbolPosition === 'before' ? (this.setting.symbol + formatted) : (formatted + this.setting.symbol))
* @param precision 小数点后精确位数(不传递则使用配置)
private toFixed(value: number, precision?: number): string {
precision = this.normalizePrecision(precision)
if (!precision && (precision < 0 || precision > 6)) {
throw new Error('invalid precision \'' + precision + '\'')
value = this.parse(value) + 0.00000001
return value.toFixed(precision)
private normalizePrecision(precision: number | string | undefined): number {
if (typeof (precision) === 'number') {
precision = Number(precision)
precision = this.setting.precision
* @param value 字符串 或者 number
parse(value: number | string): number {
if (typeof value === 'number') return value
const regex = new RegExp('[^0-9-' + this.setting.decimal + ']', 'g')
const unformatted: number = parseFloat(
.replace(/\((?=\d+)(.*)\)/, '-$1') // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
.replace(this.setting.decimal, '.') // make sure decimal point is standard
return !isNaN(unformatted) ? unformatted : 0