why do convert numbers to string in Javascript using tostring method? - javascript

I was wondering why do people have to convert numbers to string. What are the practical uses for that kind of conversion?
Similarly why do developers use parseInt or parseFloat to convert a string to a number.
thanks

The variable’s data type is the JavaScript scripting engine’s interpretation of the type of data that variable is currently holding. A string variable holds a string; a number variable holds a number value, and so on. However, unlike many other languages, in JavaScript, the same variable can hold different types of data, all within the same application. This is a concept known by the terms loose typing and dynamic typing, both of which mean that a JavaScript variable can hold different data types at different times depending on context.
With a loosely typed language, you don’t have to declare ahead of time that a variable will be a string or a number or a boolean, as the data type is actually determined while the application is being processed. If you start out with a string variable and then want to use it as a number, that’s perfectly fine, as long as the string actually contains something that resembles a number and not something such as an email address. If you later want to treat it as a string again, that’s fine, too.
The forgiving nature of loose typing can end up generating problems. If you try to add two numbers together, but the JavaScript engine interprets the variable holding one of them as a string data type, you end up with an odd string, rather than the sum you were expecting. Context is everything when it comes to variables and data types with JavaScript.

Using parseInt and parseFloat is important if you want to do arithmetic operations on a number which is in string form. For example
"42" + 1 === "421"
parseInt("42") + 1 === 43;
The reverse is true when you want to do string operations on values which are currently a number.
42 + 1 === 43
(42 + "") + 1 === 421
Why one would want to do the former or latter though is very scenario specific. I'd wager the case of converting strings to numbers for arithmetic operations is the more prominent case though.

An example of when converting numbers to strings is useful is when you want to format the number a certain way, perhaps like a currency (1234.56 -> $1,234.56).
The converse is useful when you want to do arithmetic on strings the represent numbers. Say you have a text box were you allow the user to input a number. The value of that text box will be a string, but you need it as a number to do some arithmetic with it, so you would use parseInt and parseFloat.

string -> number:
Think about simple number validation using JS. if you can convert a string into a number, then you can validate that number before posting to a number, or for use in an arithmetic operation.
number -> string:
String concatenation mainly and display purposes. The language will most often use implicit conversion to convert the number into a string anyway, such as:
1 + " new answer has been posted"
Do remember, Javascript is a loosely typed language. This can hide a lot of implicit type-casting that is occurring.

Related

Add trailing zeros to an integer without converting to string in JS?

I'm looking to add decimals to the end of my integer. As an example:
15 => 15.00
The problem with methods like toFixed is that it will convert it into a string. I've tried to use parseFloat() and Number() on the string, but it'll convert it back to an integer with no decimals.
Is this possible? If not, can someone explain to me the logic behind why this isn't possible?
EDIT: Welp the intent was to display the number as a number, but from the going consensus, it looks like the way the only way to go about it is to use a string. Found an answer on the why: https://stackoverflow.com/a/17811916/8869701
The problem you are finding is that all numbers in javascript are floats.
a = 0.1
typeof a # "number"
b = 1
typeof b # number
They are the same.
So there is no real way to convert to from an integer to a float.
This is the reason that all of the parseFloat etc are string methods for reading and writing numbers from strings. Even if you did have floats and integers, specifying the precision of a number only really makes sense when you are displaying it to a user, and for this purpose it will be converted to a string anyway.
Depending on your exact use case you will need to use strings if you want to display with a defined precision.
When working with numbers 15 and 15.00 are equal. It wouldn't make any sense to use memory to store those trailing or leading zeros.
If that information is needed it is usually for displaying purposes. In that case a string is the right choice.
In case you need that value again you can parse the string as a number.

What is the critical difference between 'Number.parseInt()', 'Number.parseFloat()', 'Number()' or '+'?

The basic question here is how do I know when to use and
what is the critical difference between each of them:
The Number.parseInt method (or just parseInt),
Number.parseFloat method (or just parseFloat),
Number() function (or class?),
and the + operator
for converting JavaScript values (mostly String's) to numbers.
Especially since all of them give similar values and can convert String to its Number representation:
Number.parseInt("2") // returns 2
Number.parseFloat("2") // returns 2
Number("2") // returns 2
+"2" // returns 2
/* Plus a few more methods... */
eval("2") // returns 2
JSON.parse("2") // returns 2
Number.parseInt method (or just parseInt)
Ignores leading and trailing whitespace
Parses a leading number to an integer (not a floating point number)
Ignores invalid trailing data
Lets you set the base to use when interpreting the number
Will interpret text starting with 0x as hexadecimal, if another base was not provided
Returns NaN if the value could not be successfully parsed to an integer
Number.parseFloat method (or just parseFloat)
Similar to parseInt, except that it allows for a decimal part to be interpreted
Only parses to base-10
Number() function (or class?)
Similar to parseFloat, but does not allow trailing text
Will return 0 for an empty string or a string that only contains whitespace
It's not a class; when called without new, it returns a primitive number
the + operator
Basically the same as Number(), but in operator form.
eval()
Interprets and executes the given input as a JavaScript program.
Given the string "2", it will be interpreted as a numeric literal, and return that value since it's the result of the last expression in the program
Throws an error if the input was not a valid program.
JSON.parse()
Parses the textual data as JSON-serialized data.
If the data is valid, it creates the JavaScript objects/primitives that are represented by the data, and returns them.
If the data is invalid, it throws an error.
Given the string "2", it will be interpreted as a numeric literal, and return the value that was successfully parsed out of it according to the parsing requirements of JSON.
So you decide which is appropriate to use based on their capabilities.
Number.parseInt() calls the global function parseInt() in the background, same with Number.parseFloat() see: Number.parseInt ECMA and Number.parseFloat ECMA
The calls Number("2") and "+2" is identical in the background, they both call ToNumber see: Number and Unary + Operator
When you know what types you are working with, or want a guaranteed type back, use parseFloat and parseInt, otherwise it tends to be easier to only use Number() as it will work within all your calculations, many people choose to use the unary + operator because they find it more pleasing to read/type, but that is only based on preference as it is identical to Number().
Also, when you using parseInt(), you can specify a radix, which is useful in certain applications where you want to work in different number systems, which you cannot do with Number()
If the ECMA standard references does not explain the details for you enough, I will add a summary for you.

Data Types Validation in Javascript

I tried to search here but seems I can't find the best answer to my problem.
How can I validate if the user input is double, Float or Long (data types in JAVA) in javascript?
If you want to check for an object type you can use typeof keyword of javascript. For example if you want to check for a number you can do something like this:
typeof i === 'number'
or using regex for floating types:
^\d{0,2}(\.\d{0,2}){0,1}$
I don't think there is such a difference in javascript.
Does JavaScript have double floating point number precision?
There are not such types in javascript.
The types you said in javascript is a primitive data type called Number.
In JavaScript, all numbers are 64-bit floats. Functions like parseInt() treat their input like a signed int, but create a float. And bit-wise operators recreate the same behaviour you would expect with ints, but on floats.
The Javascript number primitive can't represent the range of values that the combination of Javas int, long and double can. If you really need to validate this anyway you could always write some kind of hack. For example, for the Java long you could:
store javaLongMaxValue as a string,
interpret your input number as a string,
left pad your input string with "0" until it is javaLongMaxValue.length long
and then compare the strings.
You would of course have to validate that the input can be interpreted as a number and handle the case when it's negative.
use if statements and parse it
parseInt('var');
parseDouble('var');
so on..
example..
if(parseInt('var')){
// code above checks if it is a integer.. returns 'true' if yes and 'false' if not
// then your code
}else if(parseDouble('var')){
// your code
}
.. so on

Is it possible to check for a possible conversion in JavaScript?

In JavaScript, variables are loosely typed, so the number 5 and the string "5" may both be treated as a number by several operators. However, is there a generic way to find out JavaScripts conversion abilites in at tunrime, or is it just the overloading of operators for several types that make the loose typing possible?
For example, given a variable a and a string containing a type name type_canditate, is there any way to ask JavaScript, if a may convert to type_candidate in a feasable manner, in contrast to the hard typing operators like instanceof? For example, "5" instanceof Number evaluates false, while Math.sin("5") is perfectly feasable. For numbers, one can obviuosly check if parseFloat(some_number) evaluates to NaN, but this is a special case for numbers.
So, is there any generic way of naming types, and check if some variable may convert to a given type in a useful manner?
There are three primitive data types in JavaScript: string, number and boolean.
Anything can be converted to a string or boolean:
All objects convert to true (except null, which becomes false - I only mention it here because typeof null gives object)
All objects have a built-in toString method which is called when converting to a string.
Converting a number to a string is done by giving the string representation of the number (ie. 5 becomes "5")
Numbers convert to boolean true, unless it's 0 which becomes false.
Converting to a number is a little trickier, but technically possible. If it can find a valid number, then it becomes that number. Otherwise, it becomes NaN.
So basically... any type can become any other type through casting in this way. The only time you have anything resembling an "error condition" is NaN.

JSON.parse parses / converts big numbers incorrectly

My problem is really simple but I'm not sure if there's a "native" solution using JSON.parse.
I receive this string from an API :
{ "key" : -922271061845347495 }
When I'm using JSON.parse on this string, it turns into this object:
{ "key" : -922271061845347500 }
As you can see, the parsing stops when the number is too long (you can check this behavior here). It has only 15 exact digits, the last one is rounded and those after are set to 0. Is there a "native" solution to keep the exact value ? (it's an ID so I can't round it)
I know I can use regex to solve this problem but I'd prefer to use a "native" method if it exists.
Your assumption that the parsing stops after certain digits is incorrect.
It says here:
In JavaScript all numbers are floating-point numbers. JavaScript uses
the standard 8 byte IEEE floating-point numeric format, which means
the range is from:
±1.7976931348623157 x 10308 - very large, and ±5 x 10-324 - very small.
As JavaScript uses floating-point numbers the accuracy is only assured
for integers between: -9007199254740992 (-253) and 9007199254740992
(253)
You number lies outside the "accurate" range hence it is converted to the nearest representation of the JavaScript number. Any attempt to evaluate this number (using JSON.parse, eval, parseInt) will cause data loss. I therefore recommend that you pass the key as a string. If you do not control the API, file a feature request.
The number is too big to be parsed correctly.
One solution is:
Preprocessing your string from API to convert it into string before parsing.
Preform normal parsing
Optionally, you could convert it back into number for your own purpose.
Here is the RegExp to convert all numbers in your string (proceeded with :) into strings:
// convert all number fields into strings to maintain precision
// : 922271061845347495, => : "922271061845347495",
stringFromApi = stringFromApi.replace(/:\s*(-?\d+),/g, ': "$1",');
Regex explanation:
\s* any number of spaces
-? one or zero '-' symbols (negative number support)
\d+ one or more digits
(...) will be put in the $1 variable

Categories