Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

javascript - Convert 1 integer to 1.0 - (must not be string)

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...