Created
October 18, 2018 21:48
-
-
Save gabemeola/b1c5a2220dd9a4695ed5f22ca826e7db to your computer and use it in GitHub Desktop.
truncate float to decimal point
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
export default function truncateToDecimal(number, precision = 0) { | |
const floatStr = number.toString(); | |
const index = floatStr.indexOf('.'); | |
// Return number if not a float | |
if (index === -1) { | |
return number; | |
} | |
// Truncate the string starting at the decimal plus any added precision | |
// Increment by 1 to include the specified precision | |
const truncated = floatStr.substring(0, index + precision + 1); | |
// Return the truncated float | |
return parseFloat(truncated); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment