Skip to content

Instantly share code, notes, and snippets.

@eczn
Last active August 12, 2023 16:56
Show Gist options
  • Save eczn/480cb2688eef80030f7c7a2e09342fd5 to your computer and use it in GitHub Desktop.
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)
/**
* 实现任意 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