Number Truncation in JavaScript

Samantha Ming
DailyJS
Published in
3 min readApr 8, 2019

--

CodeTidbit by SamanthaMing.com

Use Math.trunc() to truncate a floating point number and return its integer part. This function doesn't do any rounding, it simply removes all the digits following the decimal. Now you have a whole number, yay 🎊

const number = 80.6// Old Way
number < 0 ? Math.ceil(number) : Math.floor(number);
// 80
// ✅ES6 Way
const es6 = Math.trunc(number);
// 80

Example

Math.trunc() simply truncates (cuts off) the dots and the digits to the right of it. No matter whether the argument is a positive or negative number.

Math.trunc(80.9); // 80
Math.trunc(80.8); // 80
Math.trunc(80.8); // 80
Math.trunc(80.6); // 80
Math.trunc(80.5); // 80
Math.trunc(80.4); // 80
Math.trunc(80.3); // 80
Math.trunc(80.2); // 80
Math.trunc(80.1); // 80
Math.trunc(-80.1); // -80

Now let’s see some examples with non-number arguments:

Math.trunc('80.1'); // 80
Math.trunc('hello'); // NaN
Math.trunc(NaN); // NaN
Math.trunc(undefined); // NaN
Math.trunc(); // NaN

Number truncation using parseInt

You can get a similar result using parseInt

parseInt(80.1); // 80
parseInt(-80.1); // -80

--

--

Samantha Ming
DailyJS

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛