最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to account for 0 and 0.00 - Stack Overflow

programmeradmin8浏览0评论

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

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

Share Improve this question asked Nov 2, 2013 at 1:51 LynxLynx 1,4825 gold badges35 silver badges63 bronze badges 4
  • > 'Maybe parseFloat?' Sounds like you're answering your own question, there :) – Christian Ternus Commented Nov 2, 2013 at 1:53
  • You've already answered your question. Use parseFloat. =) – Guilherme Sehn Commented Nov 2, 2013 at 1:53
  • Why don't you try parseFloat and see what happens? – Qantas 94 Heavy Commented Nov 2, 2013 at 1:54
  • parseFloat wasn't working for me but with some of these suggestions that might work thanks everyone! – Lynx Commented Nov 2, 2013 at 2:06
Add a ment  | 

5 Answers 5

Reset to default 4

You could use parseFloat and pare against 0

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

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

value !== 0

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()

Perhaps you might try a regular expression match?

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

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.

发布评论

评论列表(0)

  1. 暂无评论