BaconJuice
BaconJuice

Reputation: 3769

How to validate number against 0.5 incremental using Javascript

I'm trying to validate a javascript string against 0.5 incrementals. So for exmaple..

var number = 1      //true
var number = 1.2    //false
var number = 1.5    //true
var number = 2.8    //false
var number = 4      //true
var number = 0.5    //true
var number = 10.4   //false

I'm wondering if someone can help me get started with something like this. Would perhaps regex be involved?

function validateNumber(value){
    //Do validation
}

Thank you for reading.

Upvotes: 3

Views: 2708

Answers (4)

Ruben Serrate
Ruben Serrate

Reputation: 2783

Since times 2 is one of the most efficient operations, this is probably faster than using %:

function validateNumber(value) {
   return 2*value==Math.round(2*value)
}

A faster version which doesn't need to call round.

(SO FAR THIS IS THE FASTEST SOLUTION TO THE ANSWER: http://jsperf.com/modulus-vs-times2 )

function validateNumber(value) {
   return 2*value==2*value>>0
}

Upvotes: 3

Oriol
Oriol

Reputation: 288100

It's overkill, but this could be done using HTML5 validation:

var validateNumber = (function() {
    var inp = document.createElement('input');
    inp.type = 'number';
    inp.step = 0.5;
    return function validateNumber(value) {
        inp.value = value;
        return !inp.validity.stepMismatch;
   };
})();

Of course, in practice use @AmitJoki's answer.

Upvotes: 0

vks
vks

Reputation: 67968

\d*\.?5?

Try this.This works.

See demo.

http://regex101.com/r/qZ0uP0/3

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

You can use modulus operator % which the returns remainder.

function validateNumber(value){
   return value % 0.5 == 0; 
}

Upvotes: 12

Related Questions