質問

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

役に立ちましたか?

解決

x = Math.floor(x)

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

他のヒント

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

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

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top