SHRI
SHRI

Reputation: 2466

How to truncate floating point number in jscript?

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

Upvotes: 1

Views: 244

Answers (4)

Foad S. Farimani
Foad S. Farimani

Reputation: 14016

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.

Upvotes: -2

Antti29
Antti29

Reputation: 3033

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

Upvotes: 0

BenM
BenM

Reputation: 53198

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

Upvotes: 1

Alex Walker
Alex Walker

Reputation: 2356

x = Math.floor(x)

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

Upvotes: 2

Related Questions