Explain Codes LogoExplain Codes Logo

Truncate number to two decimal places without rounding

javascript
functions
math
truncation
Nikita BarsukovbyNikita Barsukov·Jan 25, 2025
TLDR

Truncate the full-bodied number to a lean two decimal places using the Math.floor() method. Multiply the number by 100, then truncate the number using Math.floor(), and finally, get the trimmed number by dividing by 100.

const truncateToTwo = num => Math.floor(num * 100) / 100; console.log(truncateToTwo(123.456)); // 123.45 console.log(truncateToTwo(123.999)); // 123.99, Cuomo on a diet

Like a well-used chainsaw, this code effectively chops off excess digits without flinching at rounding errors.

The nitty-gritty: understanding the process

Before we can effectively truncate a number, we need to understand the operation underneath. We'll dig into the mechanics of a truncation operation which basically involves chopping off the fractional section beyond a specific point, no rounding stuff involved.

String-based approach to avoid rounding

If our friend Math.floor() happens to be on a vacation or we encounter precision-specific quirks, we can deviate a bit and employ a string-based method:

function truncateToStr(num) { const numStr = num.toString(); const matchedPortion = numStr.match(/^-?\d+(?:\.\d{0,2})?/); return matchedPortion ? Number(matchedPortion[0]) : num; } console.log(truncateToStr(123.4567)); // 123.45 console.log(truncateToStr(-123.4567)); //-123.45, negative numbers are not a problem!

This code not only truncates decimals but confronts negative numbers head-on. Hold your applause!

Streamlining code with functions

For the love of clean and optimized code, let's put our logic in a function:

const truncateDecimal = (num, decimalPlaces) => { const factor = Math.pow(10, decimalPlaces); return Math.trunc(num * factor) / factor; }; console.log(truncateDecimal(123.456789, 2)); // 123.45, bingo!

With a little help from Math.trunc, we now have a swiss army knife for chopping numbers!

Dealing with some edge-cases

Life is full of surprises and so are numbers. Some numbers refuse to be ordinary and pose unique challenges, let's address them:

Scientific notation - the party pooper

Numbers written in scientific notation are party poopers. They need to be first converted into a decimal string form, and then we can truncate freely:

function truncateScientific(num, decimalPlaces) { let numStr = num.toString(); // Convert not-so-friendly scientific notation to a friendly decimal if (/\d+\.?\d*e[+-]*\d+/i.test(numStr)) { //Pardon me for Math magic happening here! let zero = '0'; let parts = String(num).toLowerCase().split('e'); // split into coefficient and exponent parts let e = parts.pop(); // store the exponential part let l = Math.abs(e); let sign = e / l; let coeff_array = parts[0].split('.'); if (sign === -1) { coeff_array[0] = Math.abs(coeff_array[0]); numStr = zero + '.' + new Array(l).join(zero) + coeff_array.join(''); } else { let dec = coeff_array[1]; if (dec) l = l - dec.length; numStr = coeff_array.join('') + new Array(l + 1).join(zero); // voila! we got a decimal string! } } return truncateToStr(numStr); // Truncate normally } console.log(truncateScientific(1.23e-5, 2)); // 0.00, phew! console.log(truncateScientific(1.23e+5, 2)); // 123000.00, phew again!

Handling Tiny Reed Richards numbers

Extremely small numbers (think Reed Richards from Fantastic Four for size comparison), once they come to JavaScript land, they might get converted to scientific notation. Our function needs to be smart enough to handle them before truncation:

console.log(truncateScientific(0.000000123456, 2)); // 0.00, well, that went smoothly!