-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(utils): 新增 roundTo 保留 n 位小数下的 x 舍 y 入
- Loading branch information
Showing
3 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
) | ||
} |