识别变量并将其强制转换为int

时间:2018-10-03 11:26:17

标签: javascript casting floating-point integer

我遇到了我想成为int的JavaScript变量的麻烦。 开始时,它看起来像int,然后我做了一些诊断,发现不是。 最终,我想将其投射到int

这是我使用的代码:

console.log(variable);
var isInt = variable % 1 === 0;
console.log('The variable is int?');
console.log(isInt);
var isFloat = +variable && variable !== (variable|0);
console.log('The variable is float?');
console.log(isFloat);

这些是结果:

2,365
The variable is int?
false
The variable is float?
NaN

检查变量是否为float的行是我从以下问题得到的: How do I check that a number is float or integer? 这是第二个答案。

NaN表示我的变量可能是string

编辑: 我的问题与作为解决方案提供的问题不同,因为我不确定我的变量是浮点数还是整数,因此我想首先确定它。 我从该问题的答案中挑选了一部分,但没有奏效。

2 个答案:

答案 0 :(得分:2)

  

请注意:parseInt()将舍去所有小数点!

如果要获取以,作为小数点的“数字”(字符串),并且希望通过舍入将它们转换为整数,则可以使用以下方法:

function toInt(x) {
  if (!isNaN(x)) return Math.round(x);
  if (typeof x == "string") x = x.replace(",", ".");
  return Math.round(parseFloat(x));
}

console.log(toInt(5));
console.log(toInt(5.5));
console.log(toInt("5"));
console.log(toInt("5.5"));
console.log(toInt("5,5"));

更短版本:

const toInt = x => Math.round(isNaN(x) ? (typeof x == "string" ? x.replace(",", ".") : x) : x);

答案 1 :(得分:-1)

在第一行中尝试

console.log(typeof variable)

这将告诉您变量的类型是否为 string ,这可能在上次检查时导致 NaN