fix: improve round function; improvement to #873 (#901)

This commit is contained in:
Timmy Braun
2026-06-22 20:07:27 +08:00
committed by GitHub
parent 5c3522f339
commit 956b51ea95
2 changed files with 6 additions and 3 deletions
+2 -3
View File
@@ -15,7 +15,6 @@ export function round (v: number, arg = 0) {
v = toNumber(v) v = toNumber(v)
arg = toNumber(arg) arg = toNumber(arg)
const amp = Math.pow(10, arg) const amp = Math.pow(10, arg)
const scaled = v * amp const scaled = (v * amp) * (1 + Number.EPSILON)
// Round half away from zero return Math.round(scaled) / amp
return Math.sign(v) * Math.round(Math.abs(scaled)) / amp
} }
+4
View File
@@ -70,6 +70,10 @@ describe('filters/math', function () {
it('should return "183.36" for 183.357,2', it('should return "183.36" for 183.357,2',
() => test('{{183.357|round: 2}}', '183.36')) () => test('{{183.357|round: 2}}', '183.36'))
it('should convert string to number', () => test('{{"2.7"|round}}', '3')) it('should convert string to number', () => test('{{"2.7"|round}}', '3'))
it('odd number 1.005 should round correctly', () => test('{{1.005|round:2}}', '1.01'))
it('odd number -1.005 should round correctly', () => test('{{num|round:2}}', { num: -1.005 }, '-1.01'))
it('odd number 9.075 should round correctly', () => test('{{9.075|round:2}}', '9.08'))
it('odd number -9.075 should round correctly', () => test('{{num|round:2}}', { num: -9.075 }, '-9.08'))
}) })
describe('times', function () { describe('times', function () {
it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6')) it('should return "6" for 3,2', () => test('{{ 3 | times: 2 }}', '6'))