Parse a float number to a string with x decimals


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

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);"


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.