首页 > 解决方案 > 将 JS 数组用作函数“存储库”时,我在哪里犯了错误?

问题描述

我需要用自定义的小数位数格式化数字。我使用简单的功能,我试图重用已经配置的“格式化功能”。

我哪里有错误?

编辑:我添加了完整的格式化程序设置,它使用http://numbrojs.com/以给定语言格式化数字。

代码:

const decimalPlacesDefaults = 2
const formatters: any = []

const createFormatter = (decimalPlaces = decimalPlacesDefaults) => {
    const formatter = numbro

    const language = formatter.languageData()
    language.delimiters = {
        decimal: ',',
        thousands: ' ',
    }

    formatter.registerLanguage(language, true)

    formatter.setDefaults({
        thousandSeparated: true,
        mantissa: decimalPlaces,
    })

    return formatter
}

const getFormatter = (decimalPlaces = decimalPlacesDefaults) => {
    // return createFormatter(decimalPlaces)   <-- when I uncomment this, everything works as expected
    const key = `f_${decimalPlaces}`

    if (formatters[key] === undefined) {
        formatters[key] = createFormatter(decimalPlaces)
    }

    return formatters[key]
}

const format = (value: string, decimalPlaces = decimalPlacesDefaultCount): string => {
    const formatter = getFormatter(decimalPlaces)

    return formatter(value).format()
}

测试:

describe('format function to custom decimal places', () => {

    it('should reflect custom decimal places for all calculations', () => {
        expect(format('123', 3)).toMatch('123,000')
        expect(format('123', 1)).toMatch('123,0')
        expect(format('23.456', 2)).toMatch('23,46')  <-- fails here with '23,5' instead of '23,46'
        expect(format('11.24', 3)).toMatch('11,240')
        expect(format('456.78', 2)).toMatch('456,78')
    })

})

标签: javascriptarraysindexingarrow-functions

解决方案


推荐阅读