Skip to content

Instantly share code, notes, and snippets.

@midknightmare666
Created October 31, 2019 07:21
Show Gist options
  • Save midknightmare666/a60913e892f4bd1dde999fe4b224477b to your computer and use it in GitHub Desktop.
Save midknightmare666/a60913e892f4bd1dde999fe4b224477b to your computer and use it in GitHub Desktop.
/**
* 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