javascript - 在没有舍入的情况下在Javascript中将double转换为int

标签 javascript casting floating-point int

在 C# 中,以下代码返回 2:

double d = 2.9;
int i = (int)d;
Debug.WriteLine(i);

然而,在 Javascript 中,我所知道的将“double”转换为“int”的唯一方法是使用 Math.round/floor/toFixed 等。有没有一种方法可以转换为 int没有四舍五入的Javascript?我知道 Number() 的性能影响,所以我宁愿尽可能避免将它转换为字符串。

最佳答案

使用parseInt()

var num = 2.9
console.log(parseInt(num, 10)); // 2

您也可以使用|

var num = 2.9
console.log(num | 0); // 2

关于javascript - 在没有舍入的情况下在Javascript中将double转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8388440/

相关文章:

javascript - React 组件未接收 props

javascript - 重试后如何获取catchWhen?

c++ - 任意精度 Gamma 函数

c - sscanf 使用 c 进行 float

javascript - 如何使用 Javascript 从对象数组中找到对象的最大长度

带有 ERB 标签的 JavaScript

c++ - 在 C++ 中使用结构作为派生类的基础

c# - 比较转换为对象的值类型

sql - SQL Server 2008 中舍入时的奇怪行为

c++ - 如何在 C++ 中正确规范化浮点值?