JS: Round/Truncate Number
Round to N Decimal Places
Here is a function to round number to n decimal places:
/* round number num to n places */ const xah_round = ((num, n) => { const m = Math.pow(10, n); return (Math.round(num * m ) / m); } ); console.log( xah_round(1.456, 0)); // 1 console.log( xah_round(1.456, 1)); // 1.5 console.log( xah_round(1.456, 2)); // 1.46 console.log( xah_round(1.456, 3)); // 1.456
Truncate to N Decimal Places
// ES2015 // truncate number num to n places const xah_round = ((num, n) => { const m = Math.pow(10, n) ; return Math.trunc(num * m ) / m; }); console.log( xah_round(1.456, 2)); // 1.45
Math.trunc
is from ES2015.
〔see Math〕
Format Number
Convert String to Number
JS: Math Object and Properties
see also Math