【问题标题】:How to limit my decimal value to 2 places on my <td>如何将我的十进制值限制为 <td> 上的 2 位
【发布时间】:2021-08-26 15:00:42
【问题描述】:

我正在查询我的数据库以返回一个双精度值。我的数据库中的这个值最多有 17 个小数位,但我只想在网页上显示 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 不是一个函数。 有没有人可以解决这个问题?

let decimal = parseFloat($("#decimal .rounded").text())
    
    window.onload = () => {

        $('.rounded').val(decimal).toFixed(2)

        console.log(decimal)   
    };

【问题讨论】:

    标签: javascript jquery html-table decimal


    【解决方案1】:

    应该是

     $('#decimal').val(decimal.toFixed(2))
    

    在号码上调用toFixed,而不是在.val()返回的jQuery对象上。

    【讨论】:

    • val() 仅用于表单控件
    【解决方案2】:

    val() 仅用于表单控件

    我会使用text(function),它会在返回修改之前为您提供当前文本以执行您需要的操作

    $('.rounded').text(function(i,curr){
        return parseFloat(curr).toFixed(2)
    })
    

    【讨论】:

    • 这也适用于我最近的问题。谢谢!
    【解决方案3】:

    除非您需要在其他地方使用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]
    

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 2018-03-10
      • 2019-01-23
      • 1970-01-01
      • 2022-01-13
      • 2020-05-15
      相关资源
      最近更新 更多