Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to convert 1 to 1.0.

I'm aware of the .toFixed() method however this converts it to a string. I need it to be an integer.

How do I do this?

EDIT: I'm just going to request back-end to sort this out as there should be no problem posting 4 instead of 4.0 as they are the same number.

Thanks for the help everyone.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
405 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...