javascript - 如何按类将 JavaScript 应用于 HTML 表格以显示 2 个小数位?
问题描述
如何按类将 JavaScript 函数应用于 HTML 表格以显示 2 个小数位?JavaScript 必须应用于特定的 HTML 表类“sal”。
默认情况下,该表将包含来自其他来源的 4 5 或 6 位小数的数据,我需要将其输出为 2 位小数。
<html>
<head>
<script>
function myFunction() {
var num = document.getElementById("sal");
var n = num.toFixed(2);
document.getElementById("sal") = n;
}
onload = myFunction()
</script>
</head>
<body>
<table class="tg" border=2px;>
<thead>
<tr>
<th class="tg-hdr1">NAME</th>
<th class="tg-hdr2">SALARY</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-namehead">Andrew</td>
<td class="tg-sal">211785.678489</td>
</tr>
<tr>
<td class="tg-namehead">Pete</td>
<td class="tg-sal">525225.7789</td>
</tr>
<tr>
<td class="tg-namehead">Jack</td>
<td class="tg-sal">98958.489</td>
</tr>
</tbody>
</body>
</html>
解决方案
使用的简短解决方案Number.prototype.toFixed(2)
:
document.querySelectorAll('.tg-sal').forEach((e)=>{
e.innerText = Number(e.innerText).toFixed(2);
})
<table class="tg" border=2px;>
<thead>
<tr>
<th class="tg-hdr1">NAME</th>
<th class="tg-hdr2">SALARY</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tg-namehead">Andrew</td>
<td class="tg-sal">211785.678489</td>
</tr>
<tr>
<td class="tg-namehead">Pete</td>
<td class="tg-sal">525225.7789</td>
</tr>
<tr>
<td class="tg-namehead">Jack</td>
<td class="tg-sal">98958.489</td>
</tr>
</tbody>
</table>
推荐阅读
- flutter - 将列表中的字符串项与另一个字符串合并
- c# - 将 Angular 2 与 .NET Framework 一起使用
- node.js - 取决于多个并行 gulp 任务的完成情况
- asp.net-core - 使用 eureka 的服务发现在 docker 容器中不起作用
- java - 删除另一个地图中嵌套地图的值
- mysql - MySQL 唯一键不用作 SELECT 的索引
- c++ - 我们可以动态地将操作插入到我们的函数中吗?
- javascript - 在 `react-tooltip` 中多行显示文本
- php - 无法使用 github.com/web-token/jwt-framework 解密 JWE 令牌
- ios - 如何使用swift在ios中使用upi深度链接打开phonepe或google pay