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.

Recommended

The Quantcast CMP broke my sites

A javascript error in CMP blocks my site.

Maggio 19, 2023

WP Gutenberg notes

Collection of notes and thoughts on Wordpress Gutenberg blocks development.

Gennaio 9, 2023

Optimizing LCP, Largest Contentful Paint result

Notes about Core Web Vitals optimization challenge

Gennaio 4, 2023

Find values recursively inside complex json objects in PHP

A PHP function to to quickly search complex, nested php structures for specific values.

Dicembre 18, 2022

Scroll to DIV by ID without jQuery

Use scrollIntoView instead of jQuery animate.

Dicembre 16, 2022