Parse a float number in javascript

This small code parse a javascript float number to a string. It converts the number to a string and let…

Novembre 9, 2009

This small code parse a javascript float number to a string. It converts the number to a string and let you decide how many decimals use.

It’s very good to change the value of an input box using onfocus or onblur events, for example, when a user input a price.


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

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.