Skip to content

Instantly share code, notes, and snippets.

@Anthodpnt
Last active December 13, 2016 16:10
Show Gist options
  • Save Anthodpnt/54fb130f127a5896aa297f6a9406c692 to your computer and use it in GitHub Desktop.
Save Anthodpnt/54fb130f127a5896aa297f6a9406c692 to your computer and use it in GitHub Desktop.
Math - Round to Decimal
/**
* This gist is for Javascript beginners.
* @author: Anthony Du Pont <[email protected]>
* @site: https://www.twitter.com/JsGists
* @source: Coding Math/Keith Peters
*
* You often get floating numbers in Javascript and sometimes you need to round them and
* keep only n decimals. They are many solutions to do so but let me show you my favorite.
*
* Example:
* I have a floating number and I want it to be rounded at the 3rd decimal.
**/
const num = roundToDecimal(1.0457784523, 3); // Return 1.046
// Number: The number we want to round.
// Places: The number of decimals we want to keep.
function roundToDecimal(number, places) {
const multiplier = Math.pow(10, places); // For our example the multiplier will be 10 * 10 * 10 = 1000.
return Math.round(number * multiplier) / multiplier;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment