I am experiencing some strange behaviour with float numbers in a javascript array.
When I loop over the array like this:
$.each(values, function(key,data) {
console.log(key +": "+data);
})
I see the numbers correctly as follows:
4: 39.9283296
spline:167 5: -3.4983312
spline:167 6: 823.487609863281
But when I try to access the data directly using the array index like this:
console.log(data[4] + " " +data[5] + " " +data[6])
The numbers get rounded:
2 8 3
I would really apprecaite it if someone could explain what is going on here, and how I can access the original data. TIA!
Looks like you're trying to access a string like an array. Your data
variable contains a string, thus when you call data[4]
, you get the 5th character in your string.
There's the parseFloat
method for parsing your string into a float, if you want it like that.
I started with the comment, but I'll just write an answer.
You are addressing data
and think of it as your array, while in fact that is just one value. Check your first value: 39.9283296
. Indices 4/5/6 are 2/8/3 accordingly. That's what you are seeing, not the "floated" numbers rounded.
Check where you get data
from, looks like you just need data
itself as your value.
Your code is like this:
$.each(values, function(key,data) {
console.log(key +": "+data);
})
So let's take a look at the first line of output:
4: 39.9283296
Ok, what is key
and what is data
?
key: "4"
data: "39.9283296" // I assume it's string according to result you got
So, what does console.log(data[4] + " " +data[5] + " " +data[6])
give you?
"39.9283296"[4] // 2
^
"39.9283296"[5] // 8
^
"39.9283296"[6] // 3
^
You got it, 2 8 3
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.