Skip to content

Instantly share code, notes, and snippets.

@joates
Last active May 17, 2016 23:16
Show Gist options
  • Save joates/6eef2c5e64f86c27312de2f766378ae5 to your computer and use it in GitHub Desktop.
Save joates/6eef2c5e64f86c27312de2f766378ae5 to your computer and use it in GitHub Desktop.
rounding float values in javascript can produce undesirable results (i.e. errors in the exponent), although certain situations can still produce inaccuracy, this fixes the common cases, ** use with caution **
// fixes rounding of float values in javascript
Number.prototype.round = function(num_places) {
return +(Math.round(this +'e+'+ num_places) +'e-'+ num_places)
}
@joates
Copy link
Author

joates commented May 17, 2016

usage:

include this snippet in your code and use it like this...
var rounded_value = float_value.round(3) /* rounds to 3 decimal places */

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment