Skip to content

Instantly share code, notes, and snippets.

@the-vampiire
Created May 19, 2017 16:33
Show Gist options
  • Select an option

  • Save the-vampiire/f5b6e7137e20005ecc88815d7df48dd0 to your computer and use it in GitHub Desktop.

Select an option

Save the-vampiire/f5b6e7137e20005ecc88815d7df48dd0 to your computer and use it in GitHub Desktop.
Number Shortener - Refactored
/**
* Refactored by Vampiire on 5/19/17.
* Now will correctly truncate regardless of how many integer digits are in place
* (previously only worked for 1 integer digit)
*
* Looks for the index value of the decimal and treats this as the start of the slice
* Seeks beyond the decimal point (+1) to the number of decimals specified by the user
* Adds a 6 at this point so it will round up correctly to the number of decimals requested
*
*/
// pass in any number and specify the number of decimal places to truncate the value to:
function theTruncanator(num, decimals){
num = num.toString();
const start = num.indexOf('.'); // start at the decimal
const end = start+1+decimals; // end 1 past the decimal place + number of decimals passed by user
if(num[end] === "5"){
num = num.slice(0,start) + num.slice(start, end) + 6;
return Number(Number(num).toFixed(2));
}
return Number(Number(num).toFixed(decimals));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment