简体   繁体   English

"Javascript检查小数是否为负"

[英]Javascript check if a decimal is negative

How would i check if a decimal is negative?我如何检查小数是否为负? Because the if statement automatically turns it into a number...因为 if 语句会自动把它变成一个数字...

Example:例子:

var x = -0.24324; 

how would i parse it so it tells me x is negative/positive?我将如何解析它,所以它告诉我x是负数/正数?

Thanks谢谢

Edit: Maybe i phrased it badly, the variable changes so something it will be positive like 0.00000001 , sometimes -0.0003423423 , sometimes 0.0000000234编辑:也许我措辞不好,变量发生了变化,所以它会像0.00000001一样积极,有时是-0.0003423423 ,有时是0.0000000234

If i put it in a if statement everything is automatically turned into 0 right?如果我把它放在 if 语句中,一切都会自动变成 0 对吗? And i can't use a parseFloat in the if statement?我不能在 if 语句中使用 parseFloat 吗?

Just check if x<\/code> less than zero since it's a number:只需检查x<\/code>是否小于零,因为它是一个数字:

if (x < 0) {
  // it's negative
}
  1. You can use isNaN()<\/code> function to check whether it is valid number or not.您可以使用isNaN()<\/code>函数来检查它是否是有效数字。<\/li>
  2. If it is, then you can check for positive or negative value.如果是,那么您可以检查正值或负值。<\/li><\/ol>

    Something like this:像这样的东西:

     var x = "-123" var y = -456; var z = '-123a'; if(!isNaN(x) && x < 0) { console.log(x + ' is negative'); } if(!isNaN(y) && y < 0) { console.log(y + ' is negative'); } if(!isNaN(z) && z < 0) { console.log(z + ' is negative'); }<\/code><\/pre>

    "

const num = -8;

// Old Way

num === 0 ? num : (num > 0 ? 1 : -1); // -1

// ✅ ES6 Way

Math.sign(num); // -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM