javascript - 将 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')
})
})
解决方案
推荐阅读
- c# - Angular 6 不显示从 Asp Net Web API 2.2 检索到的数据
- python - 为什么 PyYAML/ruamel 在 Python 2 上结合转义代理?
- c# - 如何在 .netcore/Linux 中实现 Diffie Hellman
- tensorflow - C++中的Tensorflow:成功读取LSTM编码器解码器模型的协议缓冲区
- dart - Dart 类型别名
- typo3 - Typo3 用本地文件夹路径中的大数据 URL 替换大外部图像的 src
- android - 重新创建应用程序实例时,getApplicationContext() 返回 null
- mongodb - 如何使用 mongodb 查询订购和检索数据?
- amazon-web-services - ECS服务自行启动任务
- asp.net-core - 在 ASP .Net Core 2.2 中添加 JWT 令牌后授权不起作用