Advertisement
Guest User

Untitled

a guest
Feb 13th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.55 KB | None | 0 0
  1. /*
  2. This function uses a well known method for rounding to x decimals in javascript
  3. and makes it more friendly to use. It accepts a value to round and how many
  4. decimal places we need in the returned value.
  5. */
  6.  
  7. function round(value, decimals){
  8. var factor = 1;
  9.  
  10. // ADDS DECIMAL PLACES TO FACTOR
  11. for (var i = decimals - 1; i >= 0; i--) {
  12. factor *= 10;
  13. };
  14.  
  15. // GETS RID OF EVERYTHING NOT NEEDED AND PUTS THE FLOATING POINT BACK IN PLACE
  16. return Math.round(value * factor) / factor;
  17. }
  18.  
  19. console.log("Rounded to 2 decimal places ->", round(192.34823, 2));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement