# Number Truncation in JavaScript

`const number = 80.6// Old Waynumber < 0 ? Math.ceil(number) : Math.floor(number);// 80// ✅ES6 Wayconst 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); // 80Math.trunc(80.8); // 80Math.trunc(80.8); // 80Math.trunc(80.6); // 80Math.trunc(80.5); // 80Math.trunc(80.4); // 80Math.trunc(80.3); // 80Math.trunc(80.2); // 80Math.trunc(80.1); // 80Math.trunc(-80.1); // -80`
`Math.trunc('80.1'); // 80Math.trunc('hello'); // NaNMath.trunc(NaN); // NaNMath.trunc(undefined); // NaNMath.trunc(); // NaN`

# Number truncation using parseInt

You can get a similar result using `parseInt`

`parseInt(80.1); // 80parseInt(-80.1); // -80parseInt('80.1'); // 80parseInt('hello'); // NaNparseInt(undefined); // NaNparseInt(); // NaN`

# `Math.trunc()` vs `parseInt()`

`parseInt` is mainly used for a string argument. So if you're dealing with numbers, it's way better to use `Math.trunc()`.

# The gotcha with `parseInt`

There’s a potential issue when using `parseInt`. When you pass in an argument that's not a string, in our case a number, it will first convert the value to a string using the `toString()` abstract operation. Most of the time, `parseInt` is fine. But let's look at an example where it might not be.

`const number = 1000000000000000000000.5;const result = parseInt(number);console.log(result); // 1 <-- 😱`
`const number = 1000000000000000000000.5;const result = number.toString();console.log(result); // "1e+21"`

# Browser Support

Most modern browsers support `Math.trunc()`. EXCEPT, Internet Explorer. I know 😞 So if you need support for older browsers, use the old way 😕

# Bitwise Operator Solutions

Double Bitwise NOT `~~`

`console.log(~~80.6); // 80`
`console.log(80.6 | 0); // 80`

# toFixed Solution

Frani 🍍: You also can use method .toFixed()

`(80.645).toFixed() // “80”`
`Number((80.645).toFixed()) // 80`

# Share

Written by

Written by

## Samantha Ming

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