strip decimal points from variable
Solution 1
Simply...
Math.round(quantity);
...assuming you want to round 1.7
to 2
. If not, use Math.floor
for 1.7
to 1
.
Solution 2
use parseInt();
parseInt("1.25");//returns 1
parseInt("1.85");//returns 1
parseInt(1.25);//returns 1
parseInt(1.85);//returns 1
Solution 3
Use number = ~~number
This is the fastest substitute to Math.floor()
Solution 4
parseInt is the slowest method math.floor is the 2nd slowest method
faster methods not listed here are:
var myInt = 1.85 | 0; myInt = 1;
var myInt = 1.85 >> 0; myInt = 1;
Speed tests done here: http://jsperf.com/math-floor-vs-math-round-vs-parseint/2
Solution 5
Use Math.trunc()
. It does exactly what you ask. It strips the decimal.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
Related videos on Youtube
Zac
Updated on July 09, 2022Comments
-
Zac almost 2 years
ok i know this is probably really easy but I am floundering.. I have a series of variables that have a decimal point and a few zeros. How do I strip the variable so it goes from 1.000 to 1 ? Dont think this is that important but the numbers are generated from an xml file that I am grabbing with jquery like ...
var quantity = $("QTY",this).text();
Thanks in advance for any help!
-
Ashish almost 9 yearsI guess this is one of the best ways to strip decimal points from a number
-
Kris Boyd about 7 yearsBased on this test, I would say unless you are dedicated to people using your Safari browser... The trade off of "fastest" vs the obscurity of ~~ to debugging is not worth doing this. Math.floor() gives intent as well as performance. Its very important to make sure readability isn't completely tossed out in favor of minor performance gains, I would use this only in an extreme case of performance boosting. jsperf.com/tilde-vs-floor
-
Jo. almost 7 yearsFor those curious about the
|
and>>
operators, you can learn more on MDN. Note:The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format.
-
dod_basim over 5 yearssometimes, JS is very cool with the syntax (#SugarCoatingForLife)
-
Adrian Lynch about 5 yearsAnd it maintains the sign, +/-
-
jason. about 2 yearsFor anyone wondering in 2022, it doesn't matter... as long as you're not using
parseInt
. jsben.ch/8H56M