1

I've created a code on where i can try out javascript's conditions and the code goes like this: the user enter's a decimal number and an alert box will say that it is a decimal number.If it is not a decimal number, an alert box will pop up and say that it is not a decimal number. However, the problem is I don't know what to put in my IF conditional statement to identify if its decimal.

Here is my code:

 var a = document.getElementById("txt1").value;

 if (a == ?){
    alert("It is a decimal number!");
 } else {
    alert("It is not a decimal number!");
 } 

I hope someone can help me out. A total beginner. Thanks!

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
user3369942
  • 11
  • 2
  • 4
  • 2
    http://stackoverflow.com/questions/2304052/check-if-a-number-has-a-decimal-place-is-a-whole-number – sinisake Mar 02 '14 at 11:31
  • `if (/^-?\d+(\.\d+)?$/.test(input))` this is might be good enough for you. also google never hurts. – gdoron Mar 02 '14 at 11:33
  • 1
    I think a further definition of what you mean by `decimal` would help. Some examples of what would and would not be acceptable inputs from a user. Edit your question and you even earn a badge. – Xotic750 Mar 02 '14 at 11:47

5 Answers5

1

The elegant way is to use regular expression but sometimes regular expressions can frustrate novice programmers. Check this example. I hope it helps you.

var a = document.getElementById("txt1").value;

if (!isNaN(parseFloat(a)) && a.toString().indexOf(".") == -1){
    alert("It is a decimal number!");
} else {
    alert("It is not a decimal number!");
}

Best regards,

Georgi Naumov
  • 4,160
  • 4
  • 40
  • 62
0

Here's an example-

var a = prompt("Type in any number");

var b = parseInt(a);

if(a !== b) {
    alert("This is a decimal number!");
}
else {
    alert("This is an integer");
}
Sam
  • 1
  • 2
0

Use RegEx.

var value = prompt('Enter decimal here senpai', '0.0');

if (/^\d*\.?\d*$/.test(value)) {
    console.log('I\'m a decimal. Nya~');
}
Chester Ayala
  • 201
  • 2
  • 8
-1
     function decimal_only(e) {

         var charCode = (e.which) ? e.which : window.event.keyCode
         if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
             return false;
         }

         if (charCode == 46) { //Now Check The Decimal only allow 1 decimal
             if (e.value.indexOf('.') > -1) {
                 return false;
             }
         }
         return true;
     } 
-2

You can use a simple check

if(a != Math.floor(a))
{
  alert("It is a decimal number!");
} else {
        alert("It is not a decimal number!");
}

or

if(a - Math.floor(a) != 0) //then its with decimal
{
    alert("It is a decimal number!");
} else {
    alert("It is not a decimal number!");
}
Saurabh Sharma
  • 2,422
  • 4
  • 20
  • 41