You can multiply the number by a power of 10, use the appropriate math methods, and divide by the same factor.
For rounding, there is Math.round
:
function myRound(num, decimals) {
var factor = Math.pow(10, decimals);
return Math.round(num * factor) / factor;
}
For truncating, ECMAScript 6 introduces Math.trunc
. For old browsers it can be polyfilled or, assuming the number will be positive, you can use Math.floor
.
function myTruncate(num, decimals) {
var factor = Math.pow(10, decimals);
return Math.trunc(num * factor) / factor;
}
Use them like
myTruncate(1.234567, 3); // 1.234
myTruncate(1.389999, 3); // 1.389
myRound(1.234567, 2); // 1.23
myRound(1.389999, 2); // 1.39