1

How to truncate float value in Jscript?

eg.

var x = 9/6

Now x contains a floating point number and it is 1.5. I want to truncate this and get the value as 1

SHRI
  • 2,406
  • 6
  • 32
  • 48
  • 2
    possible duplicate of [How can I round down a number in Javascript?](http://stackoverflow.com/questions/1435975/how-can-i-round-down-a-number-in-javascript) (because JScript and JavaScript are very similar) – Helen Nov 01 '13 at 07:23
  • @Helen Rounding down and truncating are different things altogether. They do yield the same results with positive numbers, but different with negative numbers. – Antti29 Oct 22 '14 at 11:01
  • @Antti29: The answers in the linked question also explain the difference between rounding down and truncating. – Helen Oct 22 '14 at 13:11

4 Answers4

2
x = Math.floor(x)

This will round the value of x down to the nearest integer below.

Alex Walker
  • 2,337
  • 1
  • 17
  • 32
1

Math.round() should achieve what you're looking for, but of course it'll round 1.5 to 2. If you always want to round down to the nearest integer, use Math.floor():

var x = Math.floor(9 / 6);
BenM
  • 52,573
  • 26
  • 113
  • 168
0

Math.floor() only works as the OP intended when the number is positive, as it rounds down and not towards zero. Therefore, for negative numbers, Math.ceil() must be used.

var x = 9/6;
x = (x < 0 ? Math.ceil(x) : Math.floor(x));
Antti29
  • 2,953
  • 12
  • 34
  • 36
-2

Another solution could be:

var x = parseInt(9 / 6);
Wscript.StdOut.WriteLine(x); // returns 1

the main purpose of the parseInt() function is to parse strings to integers. So I guess it might be slower than Math.floor() and methods as such.

Foad S. Farimani
  • 12,396
  • 15
  • 78
  • 193