gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:59:13 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com