首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >parseInt on currency字段返回NaN

parseInt on currency字段返回NaN
EN

Stack Overflow用户
提问于 2012-07-30 19:42:02
回答 1查看 763关注 0票数 0

我在php/mysql中有一个动态表,我通过复选框来显示/隐藏列。下面的代码片段是javascript的一部分,它隐藏并重新计算汇总列的单元格值。

代码语言:javascript
复制
function toggleVis(button) { 
// Toggle column 
cells = $$('.t'+button.name); 
cells.invoke(button.checked ? 'show' : 'hide'); 

// Recaulculate total 
$$('tr.row').each(function(row) { 
// Initialise to zero 
var total = 0; 
row.down('.total').textContent = total; 

// Sum all visible cells 
row.select('td').each(function(cell) { 
total += cell.visible() ? parseInt(cell.textContent, 10) : 0;
}); 

// Write the total in the total cell 
row.down('.total').textContent = total; 
}); 
}

当表的内容仅仅是数字时,这很有效,但我现在需要在中创建另一个包含货币值的表。这会导致total列返回NaN,可能是由于£符号。我用下面的代码在php中格式化:

代码语言:javascript
复制
     <tbody>
  <?php do { ?>
    <tr>
      <td><?php echo $row_rsMISource['Source']; ?></td>
      <td><?php echo "£".number_format($row_rsMISource['May'], 2, '.', ','); ?></td>
      <td><?php echo "£".number_format($row_rsMISource['Jun'], 2, '.', ','); ?></td>
      <td><?php echo "£".number_format($row_rsMISource['Jul'], 2, '.', ','); ?></td>
      <td><?php echo "£".number_format($row_rsMISource['Aug'], 2, '.', ','); ?></td>
      <td><?php echo "£".number_format($row_rsMISource['Total'], 2, '.', ','); ?></td>
      </tr>
    <?php } while ($row_rsMISource = mysql_fetch_assoc($rsMISource)); ?>
    </tbody>

这将输出值,例如or 10,169.62、or 7,053.00或or.0.00

是否可以将单元格设置为货币格式,同时仍然使用上面发布的js?

EN

回答 1

Stack Overflow用户

发布于 2012-07-30 19:44:38

代码语言:javascript
复制
4 + '£4'; //NaN
4 + parseFloat('£4.3'.replace(/[^\d\.]/g, '')); //8.3

这将从字符串中删除非数字字符,并将字符串强制转换为一个数字(因此得到的是8.3,而不是"44.3")。

如果您所在的国家/地区使用逗号而不是句点作为小数点分隔符,请将\.替换为,

编辑-针对您的特定示例:

代码语言:javascript
复制
row.find('td').each(function() { 
    total += $(this).is(':visible') ? parseFloat($(this).text().replace(/[^\d\.]/g, '')) : 0;
});

在那里有相当多的代码更改。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11720814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档