首页 > 解决方案 > 识别变量并转换为 int

问题描述

我想成为 JavaScript 中的变量时遇到问题int。一开始,它看起来像一个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我从这个问题中得到的行: 如何检查数字是浮点数还是整数? 这是第二个答案。

NaN意味着我的变量可能是一个string

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

标签: javascriptcastingfloating-pointinteger

解决方案


注意: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);

推荐阅读