Truncate number to two decimal places without rounding
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
.
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:
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:
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:
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:
Was this article helpful?