JavaScript:parseFloat 不工作

发布于 2024-10-16 23:07:43 字数 477 浏览 2 评论 0 原文

我正在使用 jQuery 从网页中提取一些数据,它以数组形式返回,其中包含我试图添加的以下值(.5、.25、1.25、3.75)。这是我的代码片段:

var th = 0;
    for (thisrow in objGrid) {
        var hours = objGrid[thisrow]['hours'];
        th = th+parseFloat(hours);
        console.log(hours);

        $("#msgbox").html("Showing records for week: " + thisDate + ". Total Hours for the week : " + th);
   }

在 console.log 中,我得到了几个小时 - 0, 0 , 1, 3 ,总计 4。如果我不使用 parseFloat 我仍然得到相同的结果,(以为我会得到 NaN )。我做错了什么?

I am using jQuery to pull some data from a web page, it comes back as an array with the following values (.5, .25, 1.25, 3.75) which I am trying to add. Here's my code snippet:

var th = 0;
    for (thisrow in objGrid) {
        var hours = objGrid[thisrow]['hours'];
        th = th+parseFloat(hours);
        console.log(hours);

        $("#msgbox").html("Showing records for week: " + thisDate + ". Total Hours for the week : " + th);
   }

in console.log I am getting this for the hours - 0, 0 , 1, 3 and it is totaling 4. If I don't use parseFloat I still get the same results, (thought I would get NaN). What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梨涡少年 2024-10-23 23:07:43

我认为您一定还有其他问题,因为您所描述的应该有效。例如(这是对代码的错误但直接的翻译):

var grid = [ ".5", ".25", "1.25", "3.75" ];
var th = 0;
for (x in grid){
  var h = grid[x];
  var hrs = parseFloat(h);
  th = th + hrs;
  console.log( h, hrs );
}
//   .5 0.5
//  .25 0.25
// 1.25 1.25
// 3.75 3.75

console.log( th );
// 5.75

无论如何,您应该对代码进行一些更改:

  1. 不要使用 for ( x in a ) 进行迭代一个数组;使用数字 for 循环:for (var i=0,len=a.length;i

  2. 始终 var 你的变量。您正在使用并覆盖全局 thisrow 变量。即使当您使用 for ... in 时,也要像 for (var x in o) 那样执行(除非您已在函数的前面声明了变量)。

  3. 您应该使用 th += ... 而不是 th = th + ...,因为它更短且更干燥。

  4. 您应该使用*1而不是<代码>parseFloat。它速度更快,打字更少,并且当您遇到混乱的字符串时也不会欺骗您。

I think you must have some other problem, as what you are describing should work. For example (here's a bad-but-direct translation of your code):

var grid = [ ".5", ".25", "1.25", "3.75" ];
var th = 0;
for (x in grid){
  var h = grid[x];
  var hrs = parseFloat(h);
  th = th + hrs;
  console.log( h, hrs );
}
//   .5 0.5
//  .25 0.25
// 1.25 1.25
// 3.75 3.75

console.log( th );
// 5.75

A few things you should change about your code anyhow:

  1. Don't use for ( x in a ) to iterate over an array; use a numeric for loop: for (var i=0,len=a.length;i<len;++i)

  2. Always var your variables. You're using and overwriting a global thisrow variable. Even when you use for ... in, do it like so for (var x in o) (unless you have declared your variable earlier in the function).

  3. You should use th += ... instead of th = th + ..., just because it's shorter and DRYer.

  4. You should use *1 instead of parseFloat. It's faster, less typing, and doesn't lie to you when you have a janky string.

命硬 2024-10-23 23:07:43
var hours = objGrid[thisrow]['hours']+"";

应该可以解决问题。 ParseFloat() 获取字符编号的值。

var hours = objGrid[thisrow]['hours']+"";

should do the trick. ParseFloat() takes charaster number's value.

拿命拼未来 2024-10-23 23:07:43

问题是:为什么你的小数值要四舍五入。在我自己摸索之后,我发现 for(... in ...) 构造本身正在将值向下舍入。如果直接访问数组元素,即 objGrid[0][i],则浮点数将保留其原始值,而不是四舍五入。因此,我的建议是使用标准的 for() 循环而不是 for(in)。

编辑:

对于那些不相信我的结果的人,请查看此代码片段:

var arr = [.5,.25,1.25, 3.75];

alert(arr[0]);

for(v in arr){
    alert(arr[0]);
    alert(v);
}

这是OP问题的简化版本,但原理相同。查看警报语句的结果。它将是 0.5、.5,然后是 0 ... 所有这些都来自我引用变量的方式,该变量可能指向内存中的同一位置,但在后一种情况下,对值进行四舍五入(显然)。

我自己在最新版本的 Firefox 上测试了这一点。

The question is: why are your decimal values being rounded. After poking around myself, I found that the for(... in ...) construct itself is rounding the values down. If you access the array element directly, i.e. objGrid[0][i], then the floats will retain their original value, and not be rounded. Hence, my suggestions would be to use a standard for() loop instead of for(in).

EDIT:

For those disbelieving my results, check out this code snippet:

var arr = [.5,.25,1.25, 3.75];

alert(arr[0]);

for(v in arr){
    alert(arr[0]);
    alert(v);
}

This is way simplified version of the OP's question, but same principle. Look at the results of the alert statements. It will be .5, .5, then 0 ... all from how I'm referencing the variable, which is presumably pointing to the same place in memory, but in the later case, rounding the value (apparently).

Tested this myself on the latest version of Firefox.

美人骨 2024-10-23 23:07:43

对此不确定,但尝试编写 var th = 0.0; - 也许,javascript 识别第一个整数并尝试将第二个操作数转换为整数。顺便问一下,你用什么浏览器?

Not sure about this, but try to write var th = 0.0; - maybe, javascript recognizes first integer number and tries to convert second operant to integer. By the way, what browser do you use?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文