Skip to content

Commit

Permalink
feat(utils): 新增 roundTo 保留 n 位小数下的 x 舍 y 入
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Sep 15, 2021
1 parent 55c3f88 commit aeb6886
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export * from './pMap'
export * from './readFile'
export * from './RichUrl'
export * from './rot13'
export * from './roundTo'
export * from './run'
export * from './sampleBy'
export * from './sampleIndex'
Expand Down
20 changes: 20 additions & 0 deletions src/utils/roundTo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { roundTo } from './roundTo'

describe('roundTo', () => {
test('表现正常', () => {
expect(roundTo(5.2)).toBe(5)
expect(roundTo(5.25)).toBe(5)
expect(roundTo(5.52)).toBe(6)
expect(roundTo(5.6)).toBe(6)

expect(roundTo(5.2, 1)).toBe(5.2)
expect(roundTo(5.25, 1)).toBe(5.3)
expect(roundTo(5.52, 1)).toBe(5.5)
expect(roundTo(5.6, 1)).toBe(5.6)

expect(roundTo(5.0, 0, 2)).toBe(5)
expect(roundTo(5.1, 0, 2)).toBe(5)
expect(roundTo(5.2, 0, 2)).toBe(6)
expect(roundTo(5.3, 0, 2)).toBe(6)
})
})
18 changes: 18 additions & 0 deletions src/utils/roundTo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { round } from 'lodash-uni'

/**
* 保留 n 位小数下的 x 舍 y 入。
*
* @param number 数值
* @param precision 精度
* @param threshold 舍入阈值,等于大于这个值时入,小于这个值时舍
*/
export function roundTo(number: number, precision = 0, threshold = 5): number {
const [int, decimal] = number.toFixed(precision + 2).split('.')
return round(
+`${int}.${decimal.slice(0, precision)}${
+decimal[precision] >= threshold ? '9' : '0'
}`,
precision,
)
}

0 comments on commit aeb6886

Please sign in to comment.