Skip to content

Instantly share code, notes, and snippets.

@wizard04wsu
Last active August 30, 2019 15:00
Show Gist options
  • Save wizard04wsu/8830323 to your computer and use it in GitHub Desktop.
Save wizard04wsu/8830323 to your computer and use it in GitHub Desktop.
Functions to round a number to a specified precision (i.e., a specified number of decimal places).
function roundToPrecision(num, precision){
var shifter;
precision = new Number(precision || 0);
if(precision%1 !== 0) throw new RangeError("precision must be an integer");
shifter = Math.pow(10, precision);
return Math.round(num*shifter)/shifter;
}
function floorToPrecision(num, precision){
var shifter;
precision = new Number(precision || 0);
if(precision%1 !== 0) throw new RangeError("precision must be an integer");
shifter = Math.pow(10, precision);
return Math.floor(num*shifter)/shifter;
}
function ceilToPrecision(num, precision){
var shifter;
precision = new Number(precision || 0);
if(precision%1 !== 0) throw new RangeError("precision must be an integer");
shifter = Math.pow(10, precision);
return Math.ceil(num*shifter)/shifter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment