Skip to content

Commit

Permalink
feat: round to nearest number by default
Browse files Browse the repository at this point in the history
  • Loading branch information
beenotung committed May 31, 2024
1 parent 043b9a2 commit a0c3e42
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,11 @@ type NumberOptions = {
readable?: boolean
/** @example `"tr"` to treat `3,14` as `3.14` if `readable` is true */
locale?: string
/**
* @description round `0.1 + 0.2` into `0.3` if enabled
* @default true
* */
nearest?: boolean
}
```
Expand Down
7 changes: 7 additions & 0 deletions src/core.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ describe('number parser', () => {
it('should allow negative numbers', () => {
expect(number().parse(-42)).to.equals(-42)
})
it('should round to nearest value', () => {
expect(number().parse(0.1 + 0.2)).to.equals(0.3)
})
describe('human readable format', () => {
let parser = number({ readable: true })
it('should parse k/m/b/t units', () => {
Expand All @@ -125,6 +128,10 @@ describe('number parser', () => {
expect(parser.parse('3.5B')).to.equals(3.5e9)
expect(parser.parse('3.5T')).to.equals(3.5e12)
})
it('should round to nearest integer', () => {
// instead of `64900.00000000001`
expect(parser.parse('64.9k')).to.equals(64900)
})
it('should skip spaces', () => {
expect(parser.parse('12 4')).to.equals(124)
})
Expand Down
16 changes: 16 additions & 0 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,11 @@ export type NumberOptions = {
readable?: boolean
/** @example `"tr"` to treat `3,14` as `3.14` if `readable` is true */
locale?: string
/**
* @description round `0.1 + 0.2` into `0.3` if enabled
* @default true
* */
nearest?: boolean
}
export function number(
options: NumberOptions & CustomSampleOptions<number> = {},
Expand All @@ -404,6 +409,9 @@ export function number(
})
: +input
}
if (input && options.nearest != false && typeof input == 'number') {
input = nearestNumber(input)
}
if (typeof input !== 'number') {
throw new InvalidInputError({
name: context.name,
Expand Down Expand Up @@ -518,6 +526,14 @@ function parseReadableNumber(
}
}

function nearestNumber(val: number): number {
if (Number.isInteger(val)) return val
let str = val.toLocaleString('en')
str = str.replace(/,/g, '')
val = +str
return val
}

export type FloatOptions = NumberOptions & {
toFixed?: number
toPrecision?: number
Expand Down

0 comments on commit a0c3e42

Please sign in to comment.