[英]How to limit my decimal value to 2 places on my <td>
我正在查询我的数据库以返回双精度值。 我的数据库中的这个值最多有 17 个小数位,但我只想在 web 页面上显示 2 个小数位。
这是我的 html 和桌子。 小数点的值进入 {{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 不是 function。 有人对我如何解决这个问题有解决方案吗?
let decimal = parseFloat($("#decimal .rounded").text())
window.onload = () => {
$('.rounded').val(decimal).toFixed(2)
console.log(decimal)
};
它应该是
$('#decimal').val(decimal.toFixed(2))
在号码上调用toFixed
,而不是在.val()
返回的 jQuery object 上。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.