-
Notifications
You must be signed in to change notification settings - Fork 2
/
roundTo.ts
53 lines (46 loc) · 1.54 KB
/
roundTo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* ### roundTo(number, precision)
*
* Round a floating point number to `precision` decimal places.
*
* ```js
* flocky.roundTo(3.141592653589, 4)
* // -> 3.1416
*
* flocky.roundTo(1.005, 2)
* // -> 1.01
*
* flocky.roundTo(1111.1, -2)
* // -> 1100
* ```
*
* <details>
* <summary>Implementation Details</summary>
*
* This method avoids floating-point errors by adjusting the exponent part of
* the string representation of a number instead of multiplying and dividing
* with powers of 10. The implementation is based on [this example](https://stackoverflow.com/a/60098416)
* by Lam Wei Li.
* </details>
*/
export function roundTo(number: number, precision: number): number {
const isNegative = number < 0
// We can only work with positive numbers in the next steps, use the absolute
number = Math.abs(number)
// Shift the decimal point to the right by `precision` places and round the result
// e.g. 1.456745 with precision 3 -> 1456.745 -> 1457
number = Math.round(shift(number, precision))
// Shift the decimal point back to the left by `precision` places
// e.g. 1457 with precision 3 -> 1.457
number = shift(number, -precision)
// If the original number was negative, the rounded number is too
if (isNegative) {
number = -number
}
return number
}
// Shift the decimal point of a `number` by `exponent` places
function shift(number: number, exponent: number): number {
const [numberBase, numberExponent] = `${number}e`.split('e')
return Number(`${numberBase}e${Number(numberExponent) + exponent}`)
}