![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
|
If it has a decimal
x = 4.2
If (x "has a decimal") how do i get JS to check if it has a decimal? |
|
|
|
|
|
#2 |
|
Hobbyist Programmer
|
nevermind, i figured a solution
![]() |
|
|
|
|
|
#3 |
|
Programming Guru
![]() |
if(parseInt(x) != x)
|
|
|
|
|
|
#4 |
|
Professional Programmer
Join Date: Mar 2005
Location: Glasgow, Scotland
Posts: 321
Rep Power: 4
![]() |
Another method would be to check:
// return nonzero if x has a fractional part; nonzero otherwise
function hasDecimalPoint(x) {
return (x.toString().indexOf(".") + 1);
}(Haven't tested that but I think it should work; if not, the general idea is that if there's no decimal point, indexOf(".") in the string version (x.toString()) should be -1.) Actually, assuming it does work, it will have a slightly weird behaviour if passed something that isn't a number at all... but used as it expects to be, it should be a decent solution. Last edited by mackenga; Apr 1st, 2005 at 9:56 AM. Reason: Edited code example to make it a function |
|
|
|
|
|
#5 |
|
Programming Guru
![]() ![]() ![]() |
function isDecimal(field)
{
var validTxt = /^[0-9.]+$/
var msg = "Not a valid decimal.";
if (! validTxt.test(field.value))
{
alert(msg);
return false;
}
else
{
return true;
}
}
__________________
http://jasonpowers.net "There are a thousand hacking at the branches of evil to one who is striking at the root." |
|
|
|
|
|
#6 |
|
Professional Programmer
Join Date: Mar 2005
Location: Glasgow, Scotland
Posts: 321
Rep Power: 4
![]() |
Oooh, I must confess I've never seen a regexp used in JavaScript. Is that a feature of the language or does it use some sort of library?
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|