JS: Round/Truncate Number

By Xah Lee. Date: . Last updated: .

Round to N Decimal Places

Here's 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

Here's pre ES2015 version:

// round number num to n places
function myRound (num, n) {
    var m = Math.pow(10, n) ;
    return Math.round(num * m ) / m;
}

console.log( myRound(1.456, 0)); // 1
console.log( myRound(1.456, 1)); // 1.5
console.log( myRound(1.456, 2)); // 1.46
console.log( myRound(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 JS: Math Object]

Format Number

JS: Format Number

Convert String to Number

JS: Convert String to Number

JS: Math Object and Properties

see also JS: Math Object

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth