Integers only exist in transient situations in JavaScript. You can force one by using some no-op combination of bitwise operators:
var x = 22.3;
x = ~~x;
That will result in "x" being 22
, but it's really still a floating-point value. The integer value existed during the expression evaluation of ~~x
, but when the value is stored it's back to floating point. (Sorry I edited out the bogus expression. edit no maybe it was OK; still on 1st cup of coffee ...)
Note that ~~
is two applications of the bitwise "not" operation, which will leave the (integer) value of the original number.
edit — as to your comments about posting the value to your back-end code, understand that the HTTP parameters are essentially strings anyway; that is, the numeric value is rendered as a string of decimal digits (and possibly decimal point, sign, exponent, etc). Thus, for that purpose, .toFixed()
is as good as anything else. Once the HTTP parameters reach the server, it's up to code there to interpret the parameter value as a number.
edit again — If you're posting a JSON object, then it's still the case that everything is a string. You should be using a JSON encoder to create the serialized version, and it'll leave off fractional parts of numbers that have none. You can write your own serializer, but before doing that you'd be better off spending some time figuring out what's wrong with your server-side JSON parser that keeps it from recognizing valid numbers without decimal fractions.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…