Skip to content

Commit

Permalink
fix: fix decimal mod, close koishijs/koishi#1123
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jun 25, 2023
1 parent 5383e68 commit 0824453
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
14 changes: 12 additions & 2 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -377,15 +377,25 @@ Schema.extend('string', (data, { meta }) => {
return [data]
})

function decimalShift(data: number, digits: number) {
const str = data.toString()
if (str.includes('e')) return data * Math.pow(10, digits)
const index = str.indexOf('.')
if (index === -1) return data * Math.pow(10, digits)
const frac = str.slice(index + 1)
const integer = str.slice(0, index)
if (frac.length <= digits) return +(integer + frac.padEnd(digits, '0'))
return +(integer + frac.slice(0, digits) + '.' + frac.slice(digits))
}

function isMultipleOf(data: number, min: number, step: number) {
step = Math.abs(step)
if (!/^\d+\.\d+$/.test(step.toString())) {
return (data - min) % step === 0
}
const index = step.toString().indexOf('.')
const digits = step.toString().slice(index + 1).length
const multiple = Math.pow(10, digits)
return Math.abs(data * multiple - min * multiple) % (step * multiple) === 0
return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0
}

Schema.extend('number', (data, { meta }) => {
Expand Down
6 changes: 6 additions & 0 deletions packages/core/tests/number.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,10 @@ describe('Number', () => {
expect(() => config(0.5)).to.throw()
expect(() => config(2.718)).to.throw()
})

it('number (decimal)', () => {
// https://github.com/shigma/schemastery/issues/44
const config = Schema.number().min(-1).max(0).step(0.01)
expect(config(-0.55)).to.equal(-0.55)
})
})

0 comments on commit 0824453

Please sign in to comment.