Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Number auto-formatting script 4

Status
Not open for further replies.
This should help out:

Code:
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num))
		num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10)
		cents = "0" + cents;
		
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));

	var returnValue = (((sign)?'':'-') + num + '.' + cents);

	returnValue = returnValue.toString().replace(/\,/g, ' ');
		
	return returnValue;
}
 
Thanks Mikey :)

... but this function isn't what I'm looking for, because :

- it doesn't work properly with onkeyup
- it's limited to 4 digits numbers (decimal included)
- It doesn't insert spaces between numbers
 
Something like this?

Code:
<html>
<head>
	<script type="text/javascript">

		window.onload = attachEvents;

		function attachEvents() {
			document.getElementById('myInput').onkeyup = reformatNumber;
		}

		function reformatNumber() {
			// No error checking. Assumes only ever 1 DP per number
			var text = this.value;

			// Strip off anything to the right of the DP
			var rightOfDp = '';
			var dpPos = text.indexOf('.');
			if (dpPos != -1) {
				rightOfDp = text.substr(dpPos);
				text = text.substr(0, dpPos);
			}

			var leftOfDp = '';
			var counter = 0;
			// Format the remainder into 3 char blocks, starting from the right
			for (var loop=text.length-1; loop>-1; loop--) {
				var char = text.charAt(loop);

				// Ignore existing spaces
				if (char == ' ') continue;

				leftOfDp = char + leftOfDp;
				counter++;
				if (counter % 3 == 0) leftOfDp = ' ' + leftOfDp;
			}

			// Strip leading space if present
			if (leftOfDp.charAt(0) == ' ') leftOfDp = leftOfDp.substr(1);

			this.value = leftOfDp + rightOfDp;

		}

	</script>
</head>

<body>
	<form>
		<input type="text" id="myInput" />
	</form>
</body>
</html>

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
P.S. Just so you know, this could be [!]very[/!] annoying to lots of users. As a power user, I hate it when web pages format things as I type or auto-jump the caret from one field to another... almost enough to consider never using that site again.

Perhaps consider doing it onblur instead, so that the data is formatted only when the user leaves the field?

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Sleidia,
I testing this out in a test HTML file. This worked just fine. The output I got was (and this is copy/pasted):
Code:
55 765 765.56
Isn't that example what you want?

Also, I didn't provide the code for you to use right away. It was a starting point.
 
For good measure, here is the full HTML I used:

Code:
<html>
<head>
<script>
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num))
		num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10)
		cents = "0" + cents;
		
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));

	var returnValue = (((sign)?'':'-') + num + '.' + cents);

	document.write("Original: " + returnValue + "</br>");

	returnValue = returnValue.toString().replace(/\,/g, ' ');
		
	return returnValue;
}
</script>
</head>
<body>
	<script>
		var dollarAmount = 55765765.56;
		var newDollarAmount = formatCurrency(dollarAmount);

		document.write("Formatted: " + newDollarAmount);
	</script>
</body>
</html>
 

Thanks a lot to you all.

I've decided to use Billy's example (thanks Billy).

Now I'm trying to prevent the function from running when there already are two digits after the comma.

It's very easy with PHP but I can't find a way with javascript :(

Too bad substring() doesn't accept negative parameters just like with PHP.

Is there a simple way for doing this?

 
You might be better off testing with a RegExp for that... It sounds neater than using a string search or two, certainly.

Unfortunately, my RegExp knowledge is poor, though, so I'm probably not the person to help you out if you go down that route :-(



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 

Thanks Dan :)

I too am very weak with regexp, but anyway, don't worry because I'll do it the dirty way, as usual ahaha ;)

I wonder why there is such a small number of javascript functions compared to PHP, for example.
 
Hi

I agree with Dan with a slight difference : I consider such "features" not only annoying, but irritating.

After formatted string is reassigned to the [tt]value[/tt] the cursor is moved uncontrollably. ( Sadly I experienced this with other languages too, not only JavaScript. )

No idea how Dan's script works in Explorer, but my tests are not satisfying me :
[ul]
[li]FireFox, SeaMonkey, Opera - inserting a new character in the middle of the string moves the cursor to the end[/li]
[li]Konqueror - the cursor keeps its original position, so after adding the formatting spaces in front of the cursor, the cursor will be placed relatively with one/more characters to left[/li]
[li]Midori - similar to FireFox, but moves the cursor to the end after any key press[/li]
[/ul]
I do not intend to criticize Dan's script. I just want to say I consider the idea fundamentally wrong. And I suggest to go with Dan's alternative suggestion : format the string [tt]onblur[/tt] ( and maybe unformat it [tt]onfocus[/tt] ).

Feherke.
 
Hi feherke,

I was asked to add such a script because big number are supposed to be entered into those fields.

The goal was to avoid users mistakes with long series of zeros or missing number. It's easy to write 6000000 instead of 60000000 but less easy to write 6 000 000 instead of 60 000 000.

The problem with onblur event is that, the user eyes focus is already gone to the next field so he wouldn't notice a lack of zero/number.

With onkeyup event, the script runs when the user focus is still in the field so that he can notice/fix a mistyped number.

 
Hi

I understand the reason. And I agree with the usefulness of formatting.

I just do not agree with implementing it if this means degrading the [tt]input[/tt]'s functionality.

If really needed, I would try to show the formatted string separately :
Code:
<input type="text" onkeyup="document.getElementById('formatted').innerHTML=formatCurrency(this.value)"><br>

<div>( You mean : <span id="formatted"></span> . )</div>
( Where formatCurrency() is MikeyJudd's original function. )

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top