Last active
December 16, 2015 07:49
-
-
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.
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
/** | |
* 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