Created
October 31, 2019 07:21
-
-
Save midknightmare666/a60913e892f4bd1dde999fe4b224477b to your computer and use it in GitHub Desktop.
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
/** | |
* Round a number to a given decimal point. | |
* | |
* @function preciseRound | |
* | |
* @param {Number} value The number to be rounded. | |
* @param {Number} decimals=1 The decimal places to round to (defaults to 1). | |
* @returns {Number} rounded The final rounded number. | |
* @example | |
* preciseRound(196.2000702, 1) => 196.2 | |
*/ | |
const preciseRound = (value, decimals = 1) => { | |
if (value.constructor !== Number || decimals.constructor !== Number) | |
return { ok: false, error: new TypeError('Parameter Must Be A Number') } | |
const numSign = value >= 0 ? 1 : -1 | |
const rounded = | |
Number((Math.round(value * 10 ** decimals + numSign * 0.0001) / 10 **decimals).toFixed(decimals)) | |
return rounded | |
} | |
/* what about Math.round() or Number.toFixed() you say?? | |
those are great for miNUTE numbers, they also have their own problems | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment