JavaScript Decimals

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
phppick
Forum Commoner
Posts: 57
Joined: Thu Aug 14, 2003 5:59 am

JavaScript Decimals

Post by phppick »

Weirdan | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
Hi,

I am using this function which will allow only decimals..

Code: Select all

function decOnly(i) {
	var t = i.value;
	if(t.length>0) {
		t = t.replace(/[^\d\.]+/g, ''); 
	}
	var s = t.split('.');
	if(s.length>1) {
		s[1] = s[0] + '.' + s[1];	
		s.shift(s);
	}
	i.value = s.join('');
}

<INPUT NAME="UnitPrice"  maxlength="10" onChange="decOnly(this);" onKeyUp="decOnly(this);" onKeyPress="decOnly(this);">
My Req. is, if i enter integer 22 into this textbox and press tab, it should change automatically to 22.00.
if i enter 22.30, it should remain same. i want to add decimals only in case when i enter integers.

If anything pls let me know.

Thanks
Weirdan | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: JavaScript Decimals

Post by Weirdan »

phppick wrote: My Req. is, if i enter integer 22 into this textbox and press tab, it should change automatically to 22.00.
if i enter 22.30, it should remain same. i want to add decimals only in case when i enter integers.

If anything pls let me know.

Thanks
It seems that Number::toFixed is what you need. Try this:

Code: Select all

function decOnly(i) {
   var t = i.value;
   if(t.length>0) {
      t = t.replace(/[^\d\.]+/g, '');
   }
 
   i.value = parseFloat(t).toFixed(2);
}

<INPUT NAME="UnitPrice"  maxlength="10" onChange="decOnly(this);" onKeyUp="decOnly(this);" onKeyPress="decOnly(this);">
phppick
Forum Commoner
Posts: 57
Joined: Thu Aug 14, 2003 5:59 am

Fine

Post by phppick »

hi Weirdan,

Script is good, but some problem. Please try to run your script. and try to enter 23 in the box.

Thanks
Jen
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

just don't use it onKeyUp and onKeyPress, otherwise it would convert 2 to 2.00 as you type
phppick
Forum Commoner
Posts: 57
Joined: Thu Aug 14, 2003 5:59 am

Hi

Post by phppick »

Hi Weirdan,

You are right. Many Thanks for solution.

if u have time can u pls look at my other post "Print Window"
viewtopic.php?t=42275

Jen
Post Reply