Page 1 of 1

JavaScript Decimals

Posted: Tue Dec 27, 2005 3:29 am
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]

Re: JavaScript Decimals

Posted: Tue Dec 27, 2005 5:21 am
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);">

Fine

Posted: Tue Dec 27, 2005 9:18 pm
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

Posted: Wed Dec 28, 2005 7:37 am
by Weirdan
just don't use it onKeyUp and onKeyPress, otherwise it would convert 2 to 2.00 as you type

Hi

Posted: Wed Dec 28, 2005 8:42 pm
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