Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

In JavaScript you don't have separation between integers and floats. There are only Numbers. So whenever you save your 1 in a var, he is actually 1.0. To represent it on the screen you have to use .toFixed(). It's a string representation as you said. If you want to calculate something like 1 + 2.8 as a result you will have 3.8.

Solution 3:

you can use (1).toFixed(1) and if you again want it as an integer then change it using parseFloat((1).toFixed(1));

Post a Comment for "Convert 1 Integer To 1.0 - (must Not Be String)"