Lynx
Lynx

Reputation: 1482

How to account for 0 and 0.00

Have a simple script in place that works well but doesn't account for all forms of 0 (0.0, 0.00..etc) What is the simplest way to achieve this? Maybe parseFloat?

if(value !== "0") {
 alert('No sir this cant be empty');
 return false;
}

if they put in 0 in the textbox it will return false fine. However, if they put 0.0 it will return true

Upvotes: 1

Views: 5340

Answers (5)

Sebas
Sebas

Reputation: 21542

I'd use parseInt, seems to be the simplest:

if(parseInt(value, 10) != 0) {
 alert('No sir this cant be empty');
 return false;
}

But be sure you test value against undefined, null and empty string before that.

Upvotes: 0

pobrelkey
pobrelkey

Reputation: 5973

Perhaps you might try a regular expression match?

if (value.match(/^0(?:\.0+)?$/)) {
    alert("hey!");
}

Upvotes: 0

AlbertEngelB
AlbertEngelB

Reputation: 16456

Parse it into an actual number first, similar to this:

value = parseFloat(value)

if( value === 0 ) return false;

You'll want to look into parseInt() and parseFloat()

Upvotes: 1

You could use parseFloat and compare against 0

if (parseFloat(value) !== 0) {
    // complain
}

Upvotes: 4

dooplenty
dooplenty

Reputation: 124

Yes you can parseFloat it but you shouldn't need to use quotes around your value.

value !== 0

Upvotes: 1

Related Questions