Overwrite toFixed function


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. Number.prototype.toFixed = function(fractionDigits) {
  2. var f = parseInt(fractionDigits) || 0;
  3. if( f < -20 || f > 100 ) {
  4. throw new RangeError("Precision of " + f + " fractional digits is out of range");
  5. }
  6. var x = Number(this);
  7. if( isNaN(x) ) {
  8. return "NaN";
  9. }
  10. var s = "";
  11. if(x <= 0) {
  12. s = "-";
  13. x = -x;
  14. }
  15. if( x >= Math.pow(10, 21) ) {
  16. return s + x.toString();
  17. }
  18. var m;
  19. // 10. Let n be an integer for which the exact mathematical value of
  20. // n ÷ 10^f - x is as close to zero as possible.
  21. // If there are two such n, pick the larger n.
  22. n = Math.round(x * Math.pow(10, f) );
  23.  
  24. if( n == 0 ) {
  25. m = "0";
  26. }
  27. else {
  28. // let m be the string consisting of the digits of the decimal representation of n (in order, with no leading zeroes).
  29. m = n.toString();
  30. }
  31. if( f == 0 ) {
  32. return s + m;
  33. }
  34. var k = m.length;
  35. if(k <= f) {
  36. var z = Math.pow(10, f+1-k).toString().substring(1);
  37. m = z + m;
  38. k = f+1;
  39. }
  40. if(f > 0) {
  41. var a = m.substring(0, k-f);
  42. var b = m.substring(k-f);
  43. m = a + "." + b;
  44. }
  45. return s + m;
  46. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.