70

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?

5
  • 2
    Rounding and truncating are 2 different operations. Which one are you trying to do? Commented Dec 30, 2013 at 2:10
  • .substring() is absolutely a function in javascript. Commented Jun 9, 2016 at 16:59
  • 4
    THE METHOD IS CALLED .toFixed() Commented Dec 16, 2016 at 1:23
  • 5
    don't use toFixed. it will round. e.g. (999/1000).toFixed(0) -> '1'. As @ryan says says use Math.trunc Commented Sep 28, 2017 at 21:14
  • Here's useful JSPerf: jsperf.com/different-ways-to-truncate/1 Commented Jan 7, 2018 at 10:03

6 Answers 6

136

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 
Sign up to request clarification or add additional context in comments.

6 Comments

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.
|
18

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); } 

1 Comment

For me Math.trunc(-2.2043642353916286e-15) returns zero. I have tested it in typescriptlang.org/play
14

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 

Notice: This answer was written when Math.trunc(x) was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x).

3 Comments

I don't understand why this answer was downvoted. It is the only correct way!
@BlinkyTop Because Math.trunc(x) does exactly that
@magnap when this question was answered Math.trunc(x) was fairly new and not supported by all modern browsers at the time. For example, it would not work with Microsoft Edge at the time (Edge 12 released in 2015 and onward does support it) and IE even today does not support Math.trunc(x).
10

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.

2 Comments

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()
1

Use Math.floor():

var f = 20.536; var i = Math.floor(f); // 20 

http://jsfiddle.net/J4UVV/1/

1 Comment

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
1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.