如何将 <td> 上的小数限制为 2 位
How to limit my decimal value to 2 places on my <td>
我正在向我的数据库查询 return 双精度值。我数据库中的这个值最多保留 17 位小数,但我只想在网页上显示 2 位小数。
这是我的 html 和 table。小数的值进入{{savings_percent}}
<table class="table text-light text-end">
<thead>
<tr>
<th scope="col">CHW</th>
</tr>
</thead>
<tbody class="text-end">
<tr id="decimal">
<th scope="row">%</th>
{{#with chw}}
<td class='rounded'>{{savings_percent}}</td>
{{/with}}
</tbody>
</table>
这就是我试图获取值的方式,将其转换为十进制,然后给它一个固定的两位小数。控制台给我 $(...).val(...).toFixed 不是函数。
有没有人知道我该如何解决这个问题?
let decimal = parseFloat($("#decimal .rounded").text())
window.onload = () => {
$('.rounded').val(decimal).toFixed(2)
console.log(decimal)
};
应该是
$('#decimal').val(decimal.toFixed(2))
在号码上调用 toFixed
,而不是在 .val()
返回的 jQuery 对象上调用。
val()
仅用于表单控件
我会使用 text(function)
,它会为您提供当前文本,以便您在返回修改之前执行所需的操作
$('.rounded').text(function(i,curr){
return parseFloat(curr).toFixed(2)
})
除非你需要在其他地方使用decimal
作为数字,否则不需要将其转换为数字然后再转换回字符串,只是为了截断不需要的数字。你可以简单地做:
let decimal = $("#decimal .rounded").text().substring(0, $("#decimal .rounded").text().indexOf('.') + 3);
或者,为了使其更具可读性:
let decimal = $("#decimal .rounded").text(); // retrieve the numeric string
let truncated = decimal.substring(0, decimal.indexOf('.') + 3) // get the substring from the beginning to the second character after the '.' (included)
或者您可以使用正则表达式:
let decimal = $("#decimal .rounded").text().match(/\d+\.\d{2}/)[0]
我正在向我的数据库查询 return 双精度值。我数据库中的这个值最多保留 17 位小数,但我只想在网页上显示 2 位小数。
这是我的 html 和 table。小数的值进入{{savings_percent}}
<table class="table text-light text-end">
<thead>
<tr>
<th scope="col">CHW</th>
</tr>
</thead>
<tbody class="text-end">
<tr id="decimal">
<th scope="row">%</th>
{{#with chw}}
<td class='rounded'>{{savings_percent}}</td>
{{/with}}
</tbody>
</table>
这就是我试图获取值的方式,将其转换为十进制,然后给它一个固定的两位小数。控制台给我 $(...).val(...).toFixed 不是函数。 有没有人知道我该如何解决这个问题?
let decimal = parseFloat($("#decimal .rounded").text())
window.onload = () => {
$('.rounded').val(decimal).toFixed(2)
console.log(decimal)
};
应该是
$('#decimal').val(decimal.toFixed(2))
在号码上调用 toFixed
,而不是在 .val()
返回的 jQuery 对象上调用。
val()
仅用于表单控件
我会使用 text(function)
,它会为您提供当前文本,以便您在返回修改之前执行所需的操作
$('.rounded').text(function(i,curr){
return parseFloat(curr).toFixed(2)
})
除非你需要在其他地方使用decimal
作为数字,否则不需要将其转换为数字然后再转换回字符串,只是为了截断不需要的数字。你可以简单地做:
let decimal = $("#decimal .rounded").text().substring(0, $("#decimal .rounded").text().indexOf('.') + 3);
或者,为了使其更具可读性:
let decimal = $("#decimal .rounded").text(); // retrieve the numeric string
let truncated = decimal.substring(0, decimal.indexOf('.') + 3) // get the substring from the beginning to the second character after the '.' (included)
或者您可以使用正则表达式:
let decimal = $("#decimal .rounded").text().match(/\d+\.\d{2}/)[0]