I have a array like this.
var elements=[5614,6619,7220,7320,7830,8220,0111,0112,0113,0142,0149]
Am converting every element to string so as to use with jquery autocomplete. Am using .map function to do this.
elements = elements.map(String);
output is
["5614", "6619", "7220", "7320", "7830", "8220", "73", "74", "75", "98", "149"]
Function is taking 0111,0112,0113,0142
all these values as Octal values
and converting them to decimal
.
I don't want this conversation and want to preserve leading Zero also , How can I do this , please help.
In javascript, numeric values represent in Number type. The number can be 12,-12,12.00. There is no differentiate between integers (12,-12)and floating numbers (12.00). The number can also be stored in the form of strings (“12”) Convert to a decimal using with toFixed (2) method.
Definition and Usage. The map() method creates a new array with the results of calling a function for every array element. The map() method calls the provided function once for each element in an array, in order. Note: map() does not execute the function for array elements without values.
Be default the toFixed () method removes the fractional part. It also accepts the optional argument called digits which means we need to specify the number of digits after the decimal point.
map () does not change the original array. map () is an ES5 feature (JavaScript 2009). It is fully supported in all modern browsers: Required. A function to be run for each array element.
Function is taking 0111,0112,0113,0142 all these values as Octal values and converting them to decimal.
It's not the function doing that, it's this:
var elements=[5614,6619,7220,7320,7830,8220,0111,0112,0113,0142,0149]
In loose mode, if you start a number with a 0
followed by a series of octal digits, it's octal. That's why 010 === 8
is true:
console.log(010 === 8); // true
And heaven help us, but if you have a 0
followed by a number with non-octal decimal digits (8
or 9
), it's decimal, which is why 011 === 09
and 9 === 09
are true:
console.log(011 === 09); // true
console.log(9 === 09); // true
The solution is:
Use strict mode ("use strict";
). Both legacy octal literals (010
) and legacy non-octal decimal literals (08
) are disallowed in strict mode. (If you need to write octal, you can, with the newer 0o10
format — that's the number eight.)
Don't write leading zeros on numbers (with the possible exception of a 0
just prior to a .
in a fractional number less than one)
You can't fix elements
after the fact (because it's impossible to know, once they're numbers, which ones were incorrectly written in octal), you have to fix it at the point you're creating it, e.g.:
var elements=[5614,6619,7220,7320,7830,220,111,112,113,142,149]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With