admin管理员组文章数量:1125580
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.
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.
Share Improve this question edited Feb 24, 2016 at 18:16 Peter Mortensen 31.6k22 gold badges109 silver badges133 bronze badges asked Feb 27, 2009 at 20:15 mchermmcherm 24.6k11 gold badges47 silver badges51 bronze badges 6- 108 If you didn't know it, all numbers in javascript are floats. From the specification: – some Commented Feb 28, 2009 at 2:40
- 8 4.3.20 Number Type: The type Number is a set of values representing numbers. In ECMAScript, the set of values represents the doubleprecision 64-bit format IEEE 754 values including the special “Not-a-Number” (NaN) values, positive infinity, and negative infinity. – some Commented Feb 28, 2009 at 2:41
- 13 Yes, Javascript does not have a distinct "integer" type, but it is still not uncommon to need to do this conversion. For instance, in my application users typed in a number (possibly including cents). I had to truncate the cents and display w/ commas. Step 1 was to convert to int. – mcherm Commented Feb 28, 2009 at 15:40
- 1 also useful: speed comparison of all methods jsperf.com/math-floor-vs-math-round-vs-parseint/33 – c.. Commented Jul 26, 2012 at 18:10
- 1 @karl: If I'm accepting input into a field, I might be able to control what characters I accept, but I could be doing all kinds of processing in Javascript, not just accepting user input. Even then I might want it for things like supporting paste. – mcherm Commented Oct 30, 2012 at 16:55
18 Answers
Reset to default 2242var 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 );
Math object reference
Examples
Positive// value=x // x=5 5<x<5.5 5.5<=x<6
Math.floor(value) // 5 5 5
Math.ceil(value) // 5 6 6
Math.round(value) // 5 5 6
Math.trunc(value) // 5 5 5
parseInt(value) // 5 5 5
~~value // 5 5 5
value | 0 // 5 5 5
value >> 0 // 5 5 5
value >>> 0 // 5 5 5
value - value % 1 // 5 5 5
Negative
// value=x // x=-5 -5>x>=-5.5 -5.5>x>-6
Math.floor(value) // -5 -6 -6
Math.ceil(value) // -5 -5 -5
Math.round(value) // -5 -5 -6
Math.trunc(value) // -5 -5 -5
parseInt(value) // -5 -5 -5
value | 0 // -5 -5 -5
~~value // -5 -5 -5
value >> 0 // -5 -5 -5
value >>> 0 // 4294967291 4294967291 4294967291
value - value % 1 // -5 -5 -5
Positive - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 // =900719925474099.1
// value=x x=900719925474099 x=900719925474099.4 x=900719925474099.5
Math.floor(value) // 900719925474099 900719925474099 900719925474099
Math.ceil(value) // 900719925474099 900719925474100 900719925474100
Math.round(value) // 900719925474099 900719925474099 900719925474100
Math.trunc(value) // 900719925474099 900719925474099 900719925474099
parseInt(value) // 900719925474099 900719925474099 900719925474099
value | 0 // 858993459 858993459 858993459
~~value // 858993459 858993459 858993459
value >> 0 // 858993459 858993459 858993459
value >>> 0 // 858993459 858993459 858993459
value - value % 1 // 900719925474099 900719925474099 900719925474099
Negative - Larger numbers
// x = Number.MAX_SAFE_INTEGER/10 * -1 // -900719925474099.1
// value = x // x=-900719925474099 x=-900719925474099.5 x=-900719925474099.6
Math.floor(value) // -900719925474099 -900719925474100 -900719925474100
Math.ceil(value) // -900719925474099 -900719925474099 -900719925474099
Math.round(value) // -900719925474099 -900719925474099 -900719925474100
Math.trunc(value) // -900719925474099 -900719925474099 -900719925474099
parseInt(value) // -900719925474099 -900719925474099 -900719925474099
value | 0 // -858993459 -858993459 -858993459
~~value // -858993459 -858993459 -858993459
value >> 0 // -858993459 -858993459 -858993459
value >>> 0 // 3435973837 3435973837 3435973837
value - value % 1 // -900719925474099 -900719925474099 -900719925474099
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:
Math.floor(val)
val | 0
bitwise OR~~val
bitwise NOTparseInt(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.
Note
As stated in comments, BITWISE operators operate on signed 32bit integers, therefore large numbers will be converted, example:
1234567890 | 0 => 1234567890
12345678901 | 0 => -539222987
Note: You cannot use Math.floor()
as a replacement for truncate, because Math.floor(-3.1) = -4
and not -3
!!
A correct replacement for truncate would be:
function truncate(value)
{
if (value < 0) {
return Math.ceil(value);
}
return Math.floor(value);
}
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
.
> ~~2.5
2
> ~~(-1.4)
-1
More details courtesy of James Padolsey.
For truncate:
var intvalue = Math.floor(value);
For round:
var intvalue = Math.round(value);
You can use the parseInt method for no rounding. Be careful with user input due to the 0x (hex) and 0 (octal) prefix options.
var intValue = parseInt(floatValue, 10);
EDIT: as a warning (from the comments section), please be aware that certain numeric values will be converted to their exponent form such as 1e21
which results in the incorrect decimal representation of "1"
Bit shift by 0 which is equivalent to division by 1
// >> or >>>
2.0 >> 0; // 2
2.0 >>> 0; // 2
If you want a rounded off answer on the downward side:
var intvalue = Math.floor( floatvalue );
var integer = Math.floor(4.56);
Answer = 4
If you want to round off upwards:
var intvalue = Math.ceil( floatvalue );
Answer would be = 5
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.
One more possible way — use XOR operation:
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/
To truncate:
// Math.trunc() is part of the ES6 spec
console.log(Math.trunc( 1.5 )); // returns 1
console.log(Math.trunc( -1.5 )); // returns -1
// Math.floor( -1.5 ) would return -2, which is probably not what you wanted
To round:
console.log(Math.round( 1.5 )); // 2
console.log(Math.round( 1.49 )); // 1
console.log(Math.round( -1.6 )); // -2
console.log(Math.round( -1.3 )); // -1
Math.floor() function returns the largest integer less than or equal to a given number.
console.log('Math.floor : ', Math.floor(3.5)); console.log('Math.floor : ', Math.floor(-3.5));
Math.ceil() function always rounds a number up to the next largest integer.
console.log('Math.ceil : ', Math.ceil(3.5)); console.log('Math.ceil : ', Math.ceil(-3.5));
Math.round() function returns the value of a number rounded to the nearest integer.
console.log('Math.round : ', Math.round(3.5)); console.log('Math.round : ', Math.round(-3.5));
Math.trunc() function returns the integer part of a number by removing any fractional digits.
console.log('Math.trunc : ', Math.trunc(3.5)); console.log('Math.trunc : ', Math.trunc(-3.5));
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:
intval = floatval - floatval%1;
This method also works with high value numbers where neither '|0' nor '~~' nor '>>0' work correctly:
> n=4294967295;
> n|0
-1
> ~~n
-1
> n>>0
-1
> n-n%1
4294967295
//Convert a float to integer
Math.floor(5.95)
//5
Math.ceil(5.95)
//6
Math.round(5.4)
//5
Math.round(5.5)
//6
Math.trunc(5.5)
//5
//Quick Ways
console.log(5.95| 0)
console.log(~~5.95)
console.log(5.95 >> 0)
//5
Performance
Today 2020.11.28 I perform tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.
Results
- for all browsers all solutions (except B and K) gives very similar speed results
- solutions B and K are slow
Details
I perform test case which you can run HERE
Below snippet presents differences between solutions A B C D E F G H I J K L
function A(float) {
return Math.trunc( float );
}
function B(float) {
return parseInt(float);
}
function C(float) {
return float | 0;
}
function D(float) {
return ~~float;
}
function E(float) {
return float >> 0;
}
function F(float) {
return float - float%1;
}
function G(float) {
return float ^ 0;
}
function H(float) {
return Math.floor( float );
}
function I(float) {
return Math.ceil( float );
}
function J(float) {
return Math.round( float );
}
function K(float) {
return float.toFixed(0);
}
function L(float) {
return float >>> 0;
}
// ---------
// TEST
// ---------
[A,B,C,D,E,F,G,H,I,J,K,L]
.forEach(f=> console.log(`${f.name} ${f(1.5)} ${f(-1.5)} ${f(2.499)} ${f(-2.499)}`))
This snippet only presents functions used in performance tests - it not perform tests itself!
And here are example results for chrome
If look into native Math
object in JavaScript, you get the whole bunch of functions to work on numbers and values, etc...
Basically what you want to do is quite simple and native in JavaScript...
Imagine you have the number below:
const myValue = 56.4534931;
and now if you want to round it down to the nearest number, just simply do:
const rounded = Math.floor(myValue);
and you get:
56
If you want to round it up to the nearest number, just do:
const roundedUp = Math.ceil(myValue);
and you get:
57
Also Math.round
just round it to higher or lower number depends on which one is closer to the flot number.
Also you can use of ~~
behind the float number, that will convert a float to a whole number.
You can use it like ~~myValue
...
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.
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
If you are using angularjs then simple solution as follows In HTML Template Binding
{{val | number:0}}
it will convert val into integer
go through with this link docs.angularjs.org/api/ng/filter/number
本文标签: syntaxHow do I convert a float number to a whole number in JavaScriptStack Overflow
版权声明:本文标题:syntax - How do I convert a float number to a whole number in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736666683a1946700.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论