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…

November 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

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

Count coloured cells on Google Sheets with reference

In a spreadsheet if you need to count cells based on their background you can use this code in Google…

May 22, 2020

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

February 8, 2020

Two post types share the same taxonomy in WordPress

Sharing a WordPress taxonomy between two post types is useful especially if you want to create a relation between different…

November 14, 2019

MYSQL add counter in a query

Use mysql variables to create a counter in SQL, PHP code to use an SQL counter and what does the i mean in mysqli?

November 9, 2019

Modify the language attribute based on category in WordPress

How to modify the language attribute in your Wordpress theme using a specific value

November 7, 2019

WordPress Fatal error: Unknown: Cannot use output buffering in output buffering display handlers in Unknown on line 0

How I've beat the php mysterious fatal error unknown in Wordpress caused by caching plugin WP Fastest Cache