Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created October 18, 2018 21:48
Show Gist options
  • Save gabemeola/b1c5a2220dd9a4695ed5f22ca826e7db to your computer and use it in GitHub Desktop.
Save gabemeola/b1c5a2220dd9a4695ed5f22ca826e7db to your computer and use it in GitHub Desktop.
truncate float to decimal point
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