5

I need to check if the number has decimals. Since you can't do type checking for type float or a double I came up with the the following code.

$('#storePaymentForm').submit(function() {
    var numberValue = document.getElementById("price").value;

    if (numberValue % 1 != 0) {
        return true;
    } 
    else {
        alert('U moet een bedrag invullen met twee nullen achter de commas!');
        return false;
    }
});

This code works fine when you enter a number like: 10.23 But when you enter 10.00 it returns false and shows the alert. I've tried several things, but I can't figure it out. Can anyone help me or point me in the right direction how I can check if the number has decimals. And make sure when a user enters 10.00 it returns true instead of false(which is the case right now). The input field is of type number. The input field looks like this: <input type="number" id="price" required name="price" min="0" value="0.00" step=".01">

Bas
  • 4,423
  • 8
  • 36
  • 53
  • Since the value is a string, you should really do pattern matching. – Taplar Mar 29 '19 at 15:28
  • You could `!isNaN(numberValue) && numberValue.includes(".")` This won't allow multiple `.` characters unlike `indexOf` – adiga Mar 29 '19 at 15:31
  • You have to distinguish between mathematical numbers, and Strings, which represent that numbers. You say, that "10" is not the same as "10.00", so you are not talking about Integer / non-integer detection, but a detection, if a string contains a dot character: ".", am I right? Input type=number always returns a mathematical number, there is no way to tell if "10" or "10.00" is displayed inside. – Ivan Kuckir Mar 29 '19 at 15:32

1 Answers1

-1

As the value is of type string, you could try working out if it is not a decimal:

string.indexOf(".") == -1;
Rhys Towey
  • 2,355
  • 1
  • 24
  • 35