Truncate/round whole number in JavaScript?

javascript truncate number to 2 decimal places
javascript truncate decimal to 2 places
javascript round to 2 decimals
javascript round down
javascript round up
javascript format number 2 decimals
convert number to 2 digits javascript
javascript round to nearest 10

For a script I'm writing, I need display a number that has been rounded, but not the decimal or anything past it. I've gotten down to rounding it to the third place, but I'm not sure how to go about just dropping the decimal and everything past it, as it doesn't seem like JavaScript has a substr function like PHP does.

Any recommendations?

If you have a string, parse it as an integer:

var num = '20.536';
var result = parseInt(num, 10);  // 20

If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

var num = -2147483649.536;
var result = Math.trunc(num);  // -2147483649

If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

var num = 20.536;
var result = Math.floor(num);  // 20

And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer:

var num = -20.536;
var result = num | 0;  // -20

decimal - Truncate/round whole number in JavaScript?, If you have a string, parse it as an integer: var num = '20.536'; var result = parseInt​(num, 10); // 20. If you have a number, ECMAScript 6 offers Math.trunc for  Truncating numbers in Javascript # Math.trunc () simply removes all the fractional digits. It takes one argument which is a number. If the argument is a positive number it behaves exactly the same as Math.floor ().

Travis Pessetto's answer along with mozey's trunc2 function were the only correct answers, considering how JavaScript represents very small or very large floating point numbers in scientific notation.

For example, parseInt(-2.2043642353916286e-15) will not correctly parse that input. Instead of returning 0 it will return -2.

This is the correct (and imho the least insane) way to do it:

function truncate(number)
{
    return number > 0
         ? Math.floor(number)
         : Math.ceil(number);
}

Rounding and truncating numbers in JavaScript, We can round to the nearest integer, round down or round up. JavaScript uses three methods to achieve this: Math.round() - rounds to the nearest  Definition and Usage. The round() method rounds a number to the nearest integer. Note: 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:

function truncateToInt(x)
{
    if(x > 0)
    {
         return Math.floor(x);
    }
    else
    {
         return Math.ceil(x);
    }
 }

Then:

y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3

Math.trunc(), trunc( ) Function. The Math.trunc() function in JavaScript is used to return the integer part of a floating-point number by removing the fractional digits  Math.round() will round numbers to the nearest integer. parseInt() will take a string and attempt to parse an integer from it without rounding. parseInt() is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaning parseInt('123g32ksj') will return 123, whereas parseInt

Convert the number to a string and throw away everything after the decimal.

trunc = function(n) { return Number(String(n).replace(/\..*/, "")) }

trunc(-1.5) === -1

trunc(1.5) === 1

Edit 2013-07-10

As pointed out by minitech and on second thought the string method does seem a bit excessive. So comparing the various methods listed here and elsewhere:

function trunc1(n){ return parseInt(n, 10); }
function trunc2(n){ return n - n % 1; }
function trunc3(n) { return Math[n > 0 ? "floor" : "ceil"](n); }
function trunc4(n) { return Number(String(n).replace(/\..*/, "")); }

function getRandomNumber() { return Math.random() * 10; }

function test(func, desc) {
    var t1, t2;
    var ave = 0;
    for (var k = 0; k < 10; k++) {
        t1 = new Date().getTime();
        for (var i = 0; i < 1000000; i++) {
            window[func](getRandomNumber());
        }
        t2 = new Date().getTime();
        ave += t2 - t1;
    }
    console.info(desc + " => " + (ave / 10));
}

test("trunc1", "parseInt");
test("trunc2", "mod");
test("trunc3", "Math");
test("trunc4", "String");

The results, which may vary based on the hardware, are as follows:

parseInt => 258.7
mod      => 246.2
Math     => 243.8
String   => 1373.1

The Math.floor / ceil method being marginally faster than parseInt and mod. String does perform poorly compared to the other methods.

JavaScript, More "Try it Yourself" examples below. Definition and Usage. The round() method rounds a number to the nearest integer. Note: 2.49 will be rounded down (2),  Take in the number. Multiply by significant digits after the decimal so that you can truncate to zero places with ~~. Divide that multiplier back out.

Math.trunc() function removes all the fractional digits.

For positive number it behaves exactly the same as Math.floor():

console.log(Math.trunc(89.13349)); // output is 89

For negative numbers it behaves same as Math.ceil():

console.log(Math.trunc(-89.13349)); //output is -89

JavaScript round() Method, Number Truncation in JavaScript. Use Math.trunc() to truncate a floating point number and return its integer part. This function doesn't do any rounding, it simply​  If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. Note that this differs from many languages' round() functions, which often round this case to the next integer away from zero, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5.

Number Truncation in JavaScript, Rounding means replacing a number with an approximate value that has a shorter, simpler, round towards zero (or truncate, or round away from infinity): y is the integer that is closest to x before exposing the computed digits with a limited precision (notably within standard JavaScript or ECMAScript interface bindings). I have a number in a variable, lets say 3.7. I want to return the whole number component, the "3" without rounding it up or down. I know I've done this in the past in AccessBasic, but I'm at a loss as to how to achieve it in JavaScript. I tried using toFixed(0) but that still round up.

Rounding, However, TRUNC simply truncates a number, while INT actually rounds a number down to an integer. With positive numbers, and when TRUNC is using the  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

How to use the Excel TRUNC function, If it is less than 0.5, the argument is rounded to the integer with the lower Rounding and truncating numbers in JavaScript | pawelgrzybek.com  Definition and Usage The trunc () method returns the integer part of a number. Note: This method will NOT round the number up/down to the nearest integer, but simply remove the decimals.

Comments
  • Rounding and truncating are 2 different operations. Which one are you trying to do?
  • .substring() is absolutely a function in javascript.
  • THE METHOD IS CALLED .toFixed()
  • don't use toFixed. it will round. e.g. (999/1000).toFixed(0) -> '1'. As @ryan says says use Math.trunc
  • Here's useful JSPerf: jsperf.com/different-ways-to-truncate/1
  • Math.floor() will give the wrong result for negative numbers. Consider mozey's answer below for better alternatives.
  • @JonBrooks: Thanks, but I recommended parseInt to begin with. Consider mozey’s answer for slow, complex alternatives.
  • mozey's trunc2 is actually the correct option, plus it uses integer comparison rather than string parsing which would make it much faster than parseInt, along with always returning the correct result.
  • Are you sure about Math.trunc being supported in IE 11? MDN says there is no IE support. I also tried it in IE 11 and got "Object doesn't support property or method 'trunc'".
  • @FrankTan: Ah, sorry, I had meant Edge. Luckily, it’s easy to shim.
  • For me Math.trunc(-2.2043642353916286e-15) returns zero. I have tested it in typescriptlang.org/play
  • I don't understand why this answer was downvoted. It is the only correct way!
  • parseInt and string replacement will return incorrect answers for numbers larger than 999999999999999900000.
  • my take-away from this experience: unless performance is a huge issue, just use parseInt for simplicity, otherwise implement trunc3()
  • If you use a negative number say -20.536 then you will get the wrong result for truncation as it results in -21 jsfiddle.net/zL1v5e2k