Skip to content

Instantly share code, notes, and snippets.

@beaucharman
Last active December 16, 2015 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beaucharman/5401683 to your computer and use it in GitHub Desktop.
Save beaucharman/5401683 to your computer and use it in GitHub Desktop.
roundTo( ) | JavaScript function | A JavaScript function that returns a float to a given number of decimal places, can also transpose the decimal place if needed.
/**
* RoundTo
* ------------------------------------------------------------------------
* roundTo()
* @version 1.0 | April 18th 2013
* @author Beau Charman | @beaucharman | http://www.beaucharman.me
* @link https://gist.github.com/beaucharman/5401683
* @param {float} n | the subject number we are rounding
* @param {integer} d | the number to decimal places to round to
* @param {string} dir | 'round', 'floor' or 'ceil'
* @param {integer} t | the number to decimal places to transpose to
* @return {float}
*
* A JavaScript function that returns a float to a given number
* of decimal places, can also transpose the decimal place if needed.
* ------------------------------------------------------------------------ */
var roundTo = function(n, d, dir, t) {
'use strict';
if (!n || (typeof n !== 'number')) {
return false;
}
var r, e;
d = d || 2;
t = (!t) ? d : d - t;
d = Math.pow(10, d);
t = Math.pow(10, t);
e = n * d;
r = (function() {
switch (dir.toLowerCase()) {
case 'floor': return Math.floor(e);
case 'ceil': return Math.ceil(e);
default: return Math.round(e);
}
}());
return r / t;
};
// example
console.log(roundTo(56.2223, 2, 'ceil', 0));
// => 56.23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment