首页 > 解决方案 > 如何按类将 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>

标签: javascripthtml

解决方案


使用的简短解决方案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>


推荐阅读