GitHub 6219★

Round a number to a given number of digits

JavaScript version

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);

TypeScript version

const round = (n: number, decimals: number = 0): number => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);

Examples

round(1.234567, 3); // 1.235
round(1.234567, 4); // 1.2346
Follow me on and to get more useful contents.