简体   繁体   English

浮点数正在四舍五入

[英]Float numbers is Javascript are being rounded

I am experiencing some strange behaviour with float numbers in a javascript array. 我在javascript数组中遇到了一些带有浮点数的奇怪行为。

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! 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. 您的data变量包含一个字符串,因此,当您调用data[4] ,您将在字符串中获得第5个字符。

There's the parseFloat method for parsing your string into a float, if you want it like that. 如果需要,可以使用parseFloat方法将字符串解析为浮点数。

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. 您正在处理data并将其视为数组,而实际上这只是一个值。 Check your first value: 39.9283296 . 检查您的第一个值: 39.9283296 Indices 4/5/6 are 2/8/3 accordingly. 索引4/5/6相应地为2/8/3。 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. 检查您从何处获取data ,看起来您只需要data本身即可。

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 ,什么是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? 那么, console.log(data[4] + " " +data[5] + " " +data[6])给您什么呢?

"39.9283296"[4] // 2
     ^
"39.9283296"[5] // 8
      ^
"39.9283296"[6] // 3
       ^

You got it, 2 8 3 . 您知道了, 2 8 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM