在JavaScript中将浮点数转换为整数的最佳方法是什么? [英] What is the best method to convert floating point to an integer in JavaScript?

查看:176
本文介绍了在JavaScript中将浮点数转换为整数的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中有几种不同的方法可以将浮点数转换为整数。我的问题是什么方法能提供最佳性能,最兼容,或被认为是最佳实践?

There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice?

以下是我所知道的几种方法:

Here are a few methods that I know of:

var a = 2.5;
window.parseInt(a); // 2
Math.floor(a);      // 2
a | 0;              // 2

我确定还有其他人。建议?

I'm sure there are others out there. Suggestions?

推荐答案

根据 此网站


偶尔会使用parseInt作为将浮点数转换为整数的方法。它非常适合该任务,因为如果它的参数是数字类型,它将首先转换为字符串,然后解析为数字...

parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number...

用于舍入Math.round,Math.ceil和Math.floor之间的数字到整数... ...

For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable...

这篇关于在JavaScript中将浮点数转换为整数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆