Posted By

ginoplusio on 11/04/09


Tagged

number float String decimals parseFloat parseint


Versions (?)

Parse a float number to a string with x decimals


 / Published in: JavaScript
 

URL: http://www.barattalo.it/2009/11/09/parse-a-float-number-in-javascript/

converts a number "v" to a float number and formats the string it with "d" decimals, used on input type text onblur="parseFloatString(this.value,2);"

  1. function parseFloatString (v,d) {
  2. var x = parseFloat( !v ? 0 : v);
  3. x = parseFloat( Math.round( x * Math.pow(10,d) ) ) / Math.pow(10,d);
  4. y = x + "";
  5. if (y.indexOf(".")==-1) y = x + ".";
  6. var a = y.split(".");
  7. if (a[1].length<d) for(k=a[1].length;k<d;k++) a[1]+="0";
  8. y = a[0]+"."+a[1];
  9. return y;
  10. }

Report this snippet  

You need to login to post a comment.