Last active
May 6, 2021 08:52
-
-
Save islahh/802505a107ef0ea8cdf6eef4f46ffcd5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Truncate a number to a fixed decimal point | |
Using the Math.pow() method, we can truncate a number to a certain decimal point that we provide in the function. | |
Ex. | |
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed); | |
// Examples | |
toFixed(25.198726354, 1); // 25.1 | |
toFixed(25.198726354, 2); // 25.19 | |
toFixed(25.198726354, 3); // 25.198 | |
toFixed(25.198726354, 4); // 25.1987 | |
toFixed(25.198726354, 5); // 25.19872 | |
toFixed(25.198726354, 6); // 25.198726 | |
Reference and further reading | |
https://medium.com/dailyjs/13-javascript-one-liners-thatll-make-you-look-like-a-pro-29a27b6f51cb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment