Last active
August 12, 2023 16:56
-
-
Save eczn/480cb2688eef80030f7c7a2e09342fd5 to your computer and use it in GitHub Desktop.
implementation of and increment for any number's roundding. the Math.round(x) is equivalent to genericRound(x, 1)
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
/** | |
* 实现任意 increment 的任意数字的 rounding 操作; | |
* 比如 Math.round(n) 其实就是 genericRound(n, 1) 的特化 | |
*/ | |
export function genericRound(n: number, inc: number): number { | |
if (inc === 0) return n; | |
const d = (n % inc); | |
if (d >= (inc / 2)) return n + (inc - d); | |
return n - d; | |
} | |
genericRound(23.4, 0.5) // 23.5 | |
genericRound(23.8, 0.5) // 24 | |
genericRound(23.11, 0.1) // 23.1 | |
genericRound(23.18, 0.1) // 23.2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment