Last active
August 30, 2019 15:00
-
-
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).
This file contains 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
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