alpha-numeric identifier causing problems - javascript

I am using a basic identifier which uses a unix timestamp with an appended alphanumeric section appended to it.
Everything has been working fine until recently - a couple of identifiers fail to update in the database.
I have noticed that the failing id's have all numbers and the letter E.
EG 1386953039E87 which is being transcribed as 1.386953039e+96
I am far from being a mathematician but feel that the original value is being treated as a number. I have tried using the toString() function but this has not worked for me.

Calling toString is too late because outputting 1386953039E87 has already created it as a number (or JavaScript's best guess at a number).
Try modifying your server-side code to output it surround in quotes instead, so that it gets created as a string instead of a number.
This could also be a side-effect of using jQuery's data() function. They mention in their api docs that it doesn't alter their value but it seems like your situation is proving otherwise:
Every attempt is made to convert the string to a JavaScript value
(this includes booleans, numbers, objects, arrays, and null). A value
is only converted to a number if doing so doesn't change the value's
representation. For example, "1E02" and "100.000" are equivalent as
numbers (numeric value 100) but converting them would alter their
representation so they are left as strings. The string value "100" is
converted to the number 100.
When the data attribute is an object (starts with '{') or array
(starts with '[') then jQuery.parseJSON is used to parse the string;
it must follow valid JSON syntax including quoted property names. If
the value isn't parseable as a JavaScript value, it is left as a
string.
To retrieve the value's attribute as a string without any attempt to
convert it, use the attr() method.
So it seems you need to use the attr() instead of data() for this

Related

SVG.js group is returning exponential value although I'm storing it as a string in group

Storing numeric value as String in group(some attribute) using SVG.js. How to get value as string instead of numeric exponential value.Although I'm converting value to String before adding to group. While re-fetching, group is giving exponential. How to avoid this?
Copied over from my comment:
svg.js tries to guess if the attribute you wanna get is from type number. If so, it uses parseFloat to return a number to you. If you want to have back the string value of the number use viewGroup.node.getAttribute('myVal')

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.

Converting string obtained from element's data attribute to json

I get an error with the following code. I know $.parseJSON() is sensitive to single/double quotes. I cannot think of a solution to this problem. Can you please help !
<div data-x='{"a":"1","b":"2"}'></div>
$(document).ready(function(){
var data =$.parseJSON($("div").data("x"))
alert(data.a)
})
https://jsfiddle.net/r2Lnfbpm/
jQuery's data() does type conversion, so when the data attribute is valid JSON, it's already parsed into an object, and passing an object to $.parseJSON produces an error, as it expects a string of JSON.
$(document).ready(function(){
var data = $("div").data("x");
console.log(data.a);
});
From the documentation
Every attempt is made to convert the string to a JavaScript value
(this includes booleans, numbers, objects, arrays, and null).
A value is only converted to a number if doing so doesn't change the value's
representation.
For example, "1E02" and "100.000" are equivalent as
numbers (numeric value 100) but converting them would alter their
representation so they are left as strings. The string value "100" is
converted to the number 100.
When the data attribute is an object (starts with '{') or array
(starts with '[') then jQuery.parseJSON is used to parse the string;
it must follow valid JSON syntax including quoted property names. If
the value isn't parseable as a JavaScript value, it is left as a
string.
To retrieve the value's attribute as a string without any attempt to
convert it, use the attr() method.

What format is this object's key stored in? %00*%00_data

I have an object with the following key:
*_data
However, the characters are encoded in a non-standard format that is causing my code some problems.
I saved the value of the key to a cookie, and found the following:
%00*%00_data
However, when comparing this string (using == not ===) with the value of the key, they are not equal.
Currently I am storing the key's value into a variable and using that variable as the key. However, I'm extremely curious as to what string I could compare the actual key with that would result in true.
Any help with this mystery would be greatly appreciated.
%00 is the URI-encoded UTF-8 representation of the character NUL, representing the null character. I imagine this is used here to differentiate between the actual * character and a * character which may be replaced by some library you're using.
We can get from %00*%00_data to *_data by using JavaScript's decideURIComponent() method, which, as the name suggests, decodes the URI-encoded character:
decodeURIComponent("%00*%00_data");
Based on your comments, it seems that the key variable you're comparing against is actually this string of length 8. I mention this, because the string *_data you've included in your question is of length 6, as it doesn't include the two null characters.

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

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.

Categories