I'd like to convert a float to a whole number in JavaScript. Actually, I'd like to know how to do BOTH of the standard conversions: by truncating and by rounding. And efficiently, not via converting to a string and parsing.
我想用JavaScript把浮点数转换成整数。实际上,我想知道如何进行两种标准转换:截断和舍入。而且更有效,而不是通过转换为字符串和解析。
13 个解决方案
#1
1152
var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );
// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );
数学对象引用
Examples
Positivevalue = 5.5
Math.floor(value) // 5
Math.ceil(value) // 6
Math.round(value) // 6
Math.trunc(value) // 5
parseInt(value) // 5
~~value // 5
value | 0 // 5
value >> 0 // 5
value >>> 0 // 5
value - value % 1 // 5
Negative
value = -5.5
Math.floor(value) // -6
Math.ceil(value) // -5
Math.round(value) // -5
Math.trunc(value) // -5
parseInt(value) // -5
value | 0 // -5
~~value // -5
value >> 0 // -5
value >>> 0 // 4294967291
value - value % 1 // -5
Positive - Larger numbers
value = Number.MAX_SAFE_INTEGER/10 // 900719925474099.1
Math.floor(value) // 900719925474099
Math.ceil(value) // 900719925474100
Math.round(value) // 900719925474099
Math.trunc(value) // 900719925474099
parseInt(value) // 900719925474099
value | 0 // 858993459
~~value // 858993459
value >> 0 // 858993459
value >>> 0 // 858993459
value - value % 1 // 900719925474099
Negative - Larger numbers
value = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1
Math.floor(value) // -900719925474100
Math.ceil(value) // -900719925474099
Math.round(value) // -900719925474099
Math.trunc(value) // -900719925474099
parseInt(value) // -900719925474099
value | 0 // -858993459
~~value // -858993459
value >> 0 // -858993459
value >>> 0 // 3435973837
value - value % 1 // -900719925474099
#2
260
Bitwise OR operator
A bitwise or operator can be used to truncate floating point figures and it works for positives as well as negatives:
位或运算符可用于截断浮点数,它既适用于正反两方面:
function float2int (value) {
return value | 0;
}
Results
结果
float2int(3.1) == 3
float2int(-3.1) == -3
float2int(3.9) == 3
float2int(-3.9) == -3
Performance comparison?
I've created a JSPerf test that compares performance between:
我创建了一个JSPerf测试来比较以下性能:
Math.floor(val)
- Math.floor(val)
-
val | 0
bitwise OR - 0比特或
-
~~val
bitwise NOT - ~ ~ val位
parseInt(val)
- 方法(val)
that only works with positive numbers. In this case you're safe to use bitwise operations well as Math.floor
function.
这只适用于正数。在这种情况下,您可以安全地使用位运算和数学运算。地板上的功能。
But if you need your code to work with positives as well as negatives, then a bitwise operation is the fastest (OR being the preferred one). This other JSPerf test compares the same where it's pretty obvious that because of the additional sign checking Math is now the slowest of the four.
但是如果您需要您的代码处理阳性和阴性,那么位操作是最快的(或者是首选的)。另一个JSPerf测试进行了比较,很明显,由于附加的符号检查数学现在是四个测试中最慢的。
Note
As stated in comments, BITWISE operators operate on signed 32bit integers, therefore large numbers will be converted, example:
如注释所述,位运算符对有符号的32位整数进行操作,因此将转换较大的数字,例如:
1234567890 | 0 => 1234567890
12345678901 | 0 => -539222987
#3
88
Note: You cannot use Math.floor()
as a replacement for truncate, because Math.floor(-3.1) = -4
and not -3
!!
注意:不能使用Math.floor()代替truncatetable,因为Math.floor(-3.1) = -4,而不是-3 !
A correct replacement for truncate would be:
截断的正确替代方法是:
function truncate(value)
{
if (value < 0) {
return Math.ceil(value);
}
return Math.floor(value);
}
#4
40
A double bitwise not operator can be used to truncate floats. The other operations you mentioned are available through Math.floor
, Math.ceil
, and Math.round
.
可以使用双位不操作符截断浮点数。你提到的其他操作都可以通过数学得到。地板上,数学。装天花板,Math.round。
> ~~2.5
2
> ~~(-1.4)
-1
More details courtesy of James Padolsey.
James Padolsey提供更多细节。
#5
36
For truncate:
截断:
var intvalue = Math.floor(value);
For round:
轮:
var intvalue = Math.round(value);
#6
21
You can use the parseInt method for no rounding. Be careful with user input due to the 0x (hex) and 0 (octal) prefix options.
可以使用parseInt方法进行无舍入。小心用户输入,因为0x(十六进制)和0(八进制)前缀选项。
var intValue = parseInt(floatValue, 10);
#7
16
Bit shift by 0 which is equivalent to division by 1
位移0等于除1
// >> or >>>
2.0 >> 0; // 2
2.0 >>> 0; // 2
#8
7
In your case, when you want a string in the end (in order to insert commas), you can also just use the Number.toFixed() function, however, this will perform rounding.
在您的示例中,当您希望在末尾有一个字符串(为了插入逗号)时,您还可以使用Number.toFixed()函数,但是,这将执行四舍五入。
#9
6
There are many suggestions here. The bitwise OR seems to be the simplest by far. Here is another short solution which works with negative numbers as well using the modulo operator. It is probably easier to understand than the bitwise OR:
这里有很多建议。到目前为止,这是最简单的。这是另一个简短的解决方案,它也可以使用模运算符来处理负数。它可能比bitwise更容易理解:
intval = floatval - floatval%1;
This method also works with high value numbers where neither '|0' nor '~~' nor '>>0' work correctly:
该方法也适用于“|0”、“~~”、“>>0”都不能正确工作的高数值:
> n=4294967295;
> n|0
-1
> ~~n
-1
> n>>0
-1
> n-n%1
4294967295
#10
4
One more possible way — use XOR operation:
还有一种可能的方法——使用XOR操作:
console.log(12.3 ^ 0); // 12
console.log("12.3" ^ 0); // 12
console.log(1.2 + 1.3 ^ 0); // 2
console.log(1.2 + 1.3 * 2 ^ 0); // 3
console.log(-1.2 ^ 0); // -1
console.log(-1.2 + 1 ^ 0); // 0
console.log(-1.2 - 1.3 ^ 0); // -2
Priority of bitwise operations is less then priority of math operations, it's useful. Try on https://jsfiddle.net/au51uj3r/
位运算的优先级小于数学运算的优先级,这是有用的。尝试在https://jsfiddle.net/au51uj3r/上
#11
2
To truncate:
截断:
// Math.trunc() is part of the ES6 spec
Math.trunc( 1.5 ); // returns 1
Math.trunc( -1.5 ); // returns -1
// Math.floor( -1.5 ) would return -2, which is probably not what you wanted
To round:
轮:
Math.round( 1.5 ); // 2
Math.round( 1.49 ); // 1
Math.round( -1.6 ); // -2
Math.round( -1.3 ); // -1
#12
1
If you are using angularjs then simple solution as follows In HTML Template Binding
如果您正在使用angularjs,那么在HTML模板绑定中可以使用以下简单的解决方案
{{val | number:0}}
{ { val |人数:0 } }
it will convert val into integer
它将把val转换成整数
go through with this link docs.angularjs.org/api/ng/filter/number
通过这个链接docs.angularjs.org/api/ng/filter/number
#13
0
I just want to point out that monetarily you want to round, and not trunc. Being off by a penny is much less likely, since 4.999452 * 100 rounded will give you 5, a more representative answer.
我只是想指出,从货币的角度来说,你想要的是四舍五入,而不是截断。少花一分钱是不太可能的,因为4.999452 * 100四舍五入会给你一个更有代表性的答案。
And on top of that, don't forget about banker's rounding, which is a way to counter the slightly positive bias that straight rounding gives -- your financial application may require it.
除此之外,别忘了银行家的四舍四入,这是一种方法,可以抵消你的财务申请可能需要的那种轻微的正面偏见。
Gaussian/banker's rounding in JavaScript
高斯/银行家在JavaScript的舍入
#1
1152
var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );
// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );
数学对象引用
Examples
Positivevalue = 5.5
Math.floor(value) // 5
Math.ceil(value) // 6
Math.round(value) // 6
Math.trunc(value) // 5
parseInt(value) // 5
~~value // 5
value | 0 // 5
value >> 0 // 5
value >>> 0 // 5
value - value % 1 // 5
Negative
value = -5.5
Math.floor(value) // -6
Math.ceil(value) // -5
Math.round(value) // -5
Math.trunc(value) // -5
parseInt(value) // -5
value | 0 // -5
~~value // -5
value >> 0 // -5
value >>> 0 // 4294967291
value - value % 1 // -5
Positive - Larger numbers
value = Number.MAX_SAFE_INTEGER/10 // 900719925474099.1
Math.floor(value) // 900719925474099
Math.ceil(value) // 900719925474100
Math.round(value) // 900719925474099
Math.trunc(value) // 900719925474099
parseInt(value) // 900719925474099
value | 0 // 858993459
~~value // 858993459
value >> 0 // 858993459
value >>> 0 // 858993459
value - value % 1 // 900719925474099
Negative - Larger numbers
value = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1
Math.floor(value) // -900719925474100
Math.ceil(value) // -900719925474099
Math.round(value) // -900719925474099
Math.trunc(value) // -900719925474099
parseInt(value) // -900719925474099
value | 0 // -858993459
~~value // -858993459
value >> 0 // -858993459
value >>> 0 // 3435973837
value - value % 1 // -900719925474099
#2
260
Bitwise OR operator
A bitwise or operator can be used to truncate floating point figures and it works for positives as well as negatives:
位或运算符可用于截断浮点数,它既适用于正反两方面:
function float2int (value) {
return value | 0;
}
Results
结果
float2int(3.1) == 3
float2int(-3.1) == -3
float2int(3.9) == 3
float2int(-3.9) == -3
Performance comparison?
I've created a JSPerf test that compares performance between:
我创建了一个JSPerf测试来比较以下性能:
Math.floor(val)
- Math.floor(val)
-
val | 0
bitwise OR - 0比特或
-
~~val
bitwise NOT - ~ ~ val位
parseInt(val)
- 方法(val)
that only works with positive numbers. In this case you're safe to use bitwise operations well as Math.floor
function.
这只适用于正数。在这种情况下,您可以安全地使用位运算和数学运算。地板上的功能。
But if you need your code to work with positives as well as negatives, then a bitwise operation is the fastest (OR being the preferred one). This other JSPerf test compares the same where it's pretty obvious that because of the additional sign checking Math is now the slowest of the four.
但是如果您需要您的代码处理阳性和阴性,那么位操作是最快的(或者是首选的)。另一个JSPerf测试进行了比较,很明显,由于附加的符号检查数学现在是四个测试中最慢的。
Note
As stated in comments, BITWISE operators operate on signed 32bit integers, therefore large numbers will be converted, example:
如注释所述,位运算符对有符号的32位整数进行操作,因此将转换较大的数字,例如:
1234567890 | 0 => 1234567890
12345678901 | 0 => -539222987
#3
88
Note: You cannot use Math.floor()
as a replacement for truncate, because Math.floor(-3.1) = -4
and not -3
!!
注意:不能使用Math.floor()代替truncatetable,因为Math.floor(-3.1) = -4,而不是-3 !
A correct replacement for truncate would be:
截断的正确替代方法是:
function truncate(value)
{
if (value < 0) {
return Math.ceil(value);
}
return Math.floor(value);
}
#4
40
A double bitwise not operator can be used to truncate floats. The other operations you mentioned are available through Math.floor
, Math.ceil
, and Math.round
.
可以使用双位不操作符截断浮点数。你提到的其他操作都可以通过数学得到。地板上,数学。装天花板,Math.round。
> ~~2.5
2
> ~~(-1.4)
-1
More details courtesy of James Padolsey.
James Padolsey提供更多细节。
#5
36
For truncate:
截断:
var intvalue = Math.floor(value);
For round:
轮:
var intvalue = Math.round(value);
#6
21
You can use the parseInt method for no rounding. Be careful with user input due to the 0x (hex) and 0 (octal) prefix options.
可以使用parseInt方法进行无舍入。小心用户输入,因为0x(十六进制)和0(八进制)前缀选项。
var intValue = parseInt(floatValue, 10);
#7
16
Bit shift by 0 which is equivalent to division by 1
位移0等于除1
// >> or >>>
2.0 >> 0; // 2
2.0 >>> 0; // 2
#8
7
In your case, when you want a string in the end (in order to insert commas), you can also just use the Number.toFixed() function, however, this will perform rounding.
在您的示例中,当您希望在末尾有一个字符串(为了插入逗号)时,您还可以使用Number.toFixed()函数,但是,这将执行四舍五入。
#9
6
There are many suggestions here. The bitwise OR seems to be the simplest by far. Here is another short solution which works with negative numbers as well using the modulo operator. It is probably easier to understand than the bitwise OR:
这里有很多建议。到目前为止,这是最简单的。这是另一个简短的解决方案,它也可以使用模运算符来处理负数。它可能比bitwise更容易理解:
intval = floatval - floatval%1;
This method also works with high value numbers where neither '|0' nor '~~' nor '>>0' work correctly:
该方法也适用于“|0”、“~~”、“>>0”都不能正确工作的高数值:
> n=4294967295;
> n|0
-1
> ~~n
-1
> n>>0
-1
> n-n%1
4294967295
#10
4
One more possible way — use XOR operation:
还有一种可能的方法——使用XOR操作:
console.log(12.3 ^ 0); // 12
console.log("12.3" ^ 0); // 12
console.log(1.2 + 1.3 ^ 0); // 2
console.log(1.2 + 1.3 * 2 ^ 0); // 3
console.log(-1.2 ^ 0); // -1
console.log(-1.2 + 1 ^ 0); // 0
console.log(-1.2 - 1.3 ^ 0); // -2
Priority of bitwise operations is less then priority of math operations, it's useful. Try on https://jsfiddle.net/au51uj3r/
位运算的优先级小于数学运算的优先级,这是有用的。尝试在https://jsfiddle.net/au51uj3r/上
#11
2
To truncate:
截断:
// Math.trunc() is part of the ES6 spec
Math.trunc( 1.5 ); // returns 1
Math.trunc( -1.5 ); // returns -1
// Math.floor( -1.5 ) would return -2, which is probably not what you wanted
To round:
轮:
Math.round( 1.5 ); // 2
Math.round( 1.49 ); // 1
Math.round( -1.6 ); // -2
Math.round( -1.3 ); // -1
#12
1
If you are using angularjs then simple solution as follows In HTML Template Binding
如果您正在使用angularjs,那么在HTML模板绑定中可以使用以下简单的解决方案
{{val | number:0}}
{ { val |人数:0 } }
it will convert val into integer
它将把val转换成整数
go through with this link docs.angularjs.org/api/ng/filter/number
通过这个链接docs.angularjs.org/api/ng/filter/number
#13
0
I just want to point out that monetarily you want to round, and not trunc. Being off by a penny is much less likely, since 4.999452 * 100 rounded will give you 5, a more representative answer.
我只是想指出,从货币的角度来说,你想要的是四舍五入,而不是截断。少花一分钱是不太可能的,因为4.999452 * 100四舍五入会给你一个更有代表性的答案。
And on top of that, don't forget about banker's rounding, which is a way to counter the slightly positive bias that straight rounding gives -- your financial application may require it.
除此之外,别忘了银行家的四舍四入,这是一种方法,可以抵消你的财务申请可能需要的那种轻微的正面偏见。
Gaussian/banker's rounding in JavaScript
高斯/银行家在JavaScript的舍入