Explain Codes LogoExplain Codes Logo

Get decimal portion of a number with JavaScript

javascript
decimal-extraction
math-functions
precision-control
Anton ShumikhinbyAnton Shumikhin·Sep 24, 2024
TLDR

To do a quick extraction of the decimal part of a number, subtract the whole number part and you're good to go. Here's the magic spell using Math.floor() for positive numbers and Math.ceil() for negative. Don't worry, no magic tricks up our sleeves:

const num = 123.456; const decimalPart = num - Math.floor(num); console.log(decimalPart); // Outputs: 0.456, magic in progress! const negativeNum = -123.456; const negativeDecimalPart = Math.abs(negativeNum) - Math.floor(Math.abs(negativeNum)); console.log(negativeDecimalPart); // Outputs: 0.456, even magic couldn't make it negative!

Deep diving into decimal extraction

The num - Math.floor(num) spell is quite powerful. It gives you better precision compared to the common num % 1 approach. Little hobbit be warned, float numbers could lead you astray with inaccuracies!

Treating negative numbers nicely

Negative numbers are a bit grumpy. Put on your charm spells, extract them the right way. Use Math.abs(negativeNum) before subtracting to avoid landing in the Twilight Zone:

const negativeNum = -123.456; const decimalPortion = Math.abs(negativeNum) - Math.floor(Math.abs(negativeNum)); console.log(decimalPortion); // Outputs: 0.456, viola! We've tamed the number beast!

String method for the wizards

There's also the string manipulation way. Convert the number to a string and use split("."). Now, who said being a word wizard wasn't cool?

const num = 123.456; const decimalsAsString = (num.toString().split(".")[1] || "0"); console.log(decimalsAsString); // Outputs: "456", just like casting a spell!

Precision control: Pat your floating point nicely

toFixed() lets you have a leash on your decimal places. But remember it leaves you with a string, so useState Number():

const num = 123.456; const fixedDecimals = Number((num % 1).toFixed(2)); console.log(fixedDecimals); // Outputs: 0.46, perfect...ish?

We just rounded off the rough edges there!

Avoid stepping on banana peels

False precision and floating-point annoyance, sounds like a party in JavaScript land, right? Nah, more like sneaky pitfalls:

const num = 0.1 + 0.2; const decimalPart = num - Math.floor(num); console.log(decimalPart); // Well, this ain't right now is it?

These precision rave parties... don't fret, get libraries like BigDecimal on your side for high-precision arithmetic.

More ninja techniques

Keep your math tools sharp!

Math.floor() is cool but Math.trunc() also crushes the job of obtaining the integer portion. After which, we subtract it from the original number:

const num = 123.456; const decimalPart = num - Math.trunc(num); console.log(decimalPart); // Outputs: 0.456, Math.trunc() is your new friend!

Handling the edgy ones

Those numbers on the edge, like 0.9999999999999, know how to put up a fight. But we've got a plan:

const num = 0.9999999999999; const decimalPart = num - Math.floor(num); console.log(decimalPart.toPrecision(12)); // Something smells fishy here...

Calculations are fun...said no one ever

For those heavy-duty financial applications, work around precision issues. Use integer math by scaling decimals to whole numbers. Convert them back after calculations. Win!