javascript - 识别变量并转换为 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
?
编辑:我的问题与作为解决方案提供的问题不同,因为我不确定我的变量是浮点数还是整数,因此我试图首先识别它。我从那个问题的答案中挑选了一些部分,但它并没有奏效。
解决方案
注意:
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);
推荐阅读
- android - 没有来自广告服务器的填充。带广告:无法加载广告:3
- php - 获取 HTML 滑块的 post 值并基于整数分配文本值
- ios - ios-charts:轴和网格线间歇性缺失
- c++ - 执行相同功能的不同结果[C++]
- javascript - 我可以用 Jasmine 测试 setInterval 吗?
- java - sbt 0.13.17 “编译 sbt 组件‘编译器接口’时出错”
- c# - AWS lambda 不在 CloudWatch 中写入日志
- javascript - 使用 Javascript 制作画布全屏
- mysql - go-xorm 是否可以检测 DATETIME(3) 类型?
- python - Python 缓冲区,它们是如何工作的?