<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<div id = "jsData">
</div>
</head>
<script type="text/javascript">
function test()
{
var btn = document.getElementById("123"); //读取“123”id的html
var attitude = btn.innerHTML; //读取“123”id标签的内容
console.log(attitude); //打印内容(字符型)
btn.innerHTML = parseFloat(attitude).toFixed(2); //float转number型并保留两位小数
var tab = document.getElementById("tab1") ; //读取tab1的HTML
var rows = tab.rows.length ; //获取表格的行数
var cells = tab.rows.item(0).cells.length ;//获取表格的列数
console.log(rows);
console.log(cells);
for(var i = 0; i < rows; i++) // 循环修改表格的数据,保留两位小数
{
for(var j = 0; j < cells-1; j++)
{
var tdId = "t" + i.toString() + j.toString();
var btn1 = document.getElementById(tdId);
var attitude1 = btn1.innerHTML;
console.log(attitude1);
btn1.innerHTML = parseFloat(attitude1).toFixed(2);
}
}
}
window.onload=function() // html网页打开就执行js代码
{
test();
}
</script>
<body>
<div>
<p id="123"> 123.123456789 </p>
<table id="tab1" border="1">
<tr>
<td>123</td>
<td id="t00">123.123456789</td>
<td id="t01">9655.2464654648</td>
<td id="t02">558.2316405</td>
</tr>
<tr>
<td>123</td>
<td id="t10">85.35452</td>
<td id="t11">953.23548</td>
<td id="t12">6896.25484858</td>
</tr>
</div>
</body>
</html>
js对表格中的数据进行四舍五入保留两位小数
最新推荐文章于 2023-06-28 11:57:10 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)