SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
Hybrid View
-
Aug 9, 2007, 10:29 #1
- Join Date
- Feb 2005
- Posts
- 0
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Trying to check for .00 in cost, if not add it
Hello,
I have a javascript order form and I am trying to make sure that .00 is in the price (or .50 or .45, etc) if not add .00 to the end.
Here is what I got so far but it doesn't seem to be working.
function dec(objStr){
var objNumber;
if(isNaN(objStr) && objStr!=''){
objNumber = '0.00';
}
else if(objStr==''){
objNumber = '0.00';
}
else if(objStr.indexOf('.')!=-1){
if(((objStr.length) - (objStr.indexOf('.')))>3){
objStr = objStr.substr(0,((objStr.indexOf('.'))+3));
}
if(objStr.indexOf('.')==0){
objStr = '0' + objStr;
}
var sLen = objStr.length;
var TChar = objStr.substr(sLen-3,3);
if(TChar.indexOf('.')==0){
objNumber = objStr;
}
else if(TChar.indexOf('.')==1){
objNumber = objStr + '0';
}
else if(TChar.indexOf('.')==2){
objNumber = objStr + '00';
}
}
else{
objNumber = objStr + '.00';
}
return objNumber;
}
- SteveI have a Zune and I live in Canada. Woottastic!
-
Aug 9, 2007, 11:37 #2
- Join Date
- Jun 2003
- Location
- Malden, MA
- Posts
- 142
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
For what it's worth, you should probably allow your users to be a little more flexible with their dollar inputs. You should at least accept whole dollar amounts and deal with anything you need to do to format that on the server side.
Having said that, I would use regular expressions to check your input format. Here is a function that will test to make sure that you have only digits followed by 2 decimal points. I just give an error message if it doesn't meet that format, but you can do whatever you have to do to it. You could also test to see if it was in a couple of acceptable formats, and otherwise give an error message. I would say the following are acceptable dollar input - 2, 2., 2.0, 2.00
Code Javascript:function testDollar() { var val = document.getElementById('test_dollar').value; var checkDecimal = /^\d+\.\d{2}$/; var regex = new RegExp(checkDecimal); if( !regex.test(val) ) { alert(val + " is not a valid for this field."); return false; } return true; }
Keith Rousseau
-
Aug 9, 2007, 15:42 #3
- Join Date
- Jul 2007
- Posts
- 345
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
You could use the toFixed() method of the Number object.
Code:var num = parseFloat(inputString); // get your number if (!isNaN(num) && num.toFixed(2) == num) { num = num.toFixed(2); } else { // invalid entry }
Bookmarks