strip decimal points from variable

82,467

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

Share:
82,467

Related videos on Youtube

Zac
Author by

Zac

Updated on July 09, 2022

Comments

  • Zac
    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
    Ashish almost 9 years
    I guess this is one of the best ways to strip decimal points from a number
  • Kris Boyd
    Kris Boyd about 7 years
    Based 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.
    Jo. almost 7 years
    For 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
    dod_basim over 5 years
    sometimes, JS is very cool with the syntax (#SugarCoatingForLife)
  • Adrian Lynch
    Adrian Lynch about 5 years
    And it maintains the sign, +/-
  • jason.
    jason. about 2 years
    For anyone wondering in 2022, it doesn't matter... as long as you're not using parseInt. jsben.ch/8H56M

Related