【问题标题】:JavaScript math, round to two decimal places in Jquery templateJavaScript 数学,在 Jquery 模板中四舍五入到小数点后两位
【发布时间】:2014-09-12 20:45:23
【问题描述】:

我有一些代码

{{if commission}}              
    <td>${profit - commission}</td>   
{{else}}
    <td>${profit}</td>
{{/if}}

利润 = 5;

佣金 = 2.145

结果 = 2.855999999999

我需要2.856

请帮帮我

我尝试使用(${profit - commission}).toFixed(2) - 但它不起作用。

【问题讨论】:

标签: javascript jquery jquery-templates


【解决方案1】:

简单地使用toFixed(3)。它将选择点值后面的3位值

var s=2.855999999999;
alert(s.toFixed(3))

OP: 2.856

DEMO

【讨论】:

    【解决方案2】:
    var result = 2.855999999999;
    result =   result.toFixed(2); //returns string fixed to 2 decimal places
    result =   parseFloat(result);//returns double 2 decimal places
    alert(result);
    

    【讨论】:

      【解决方案3】:

      提到在 jQuery 模板中使用

      parseFloat 应该在 ${}

      里面

      ${ parseFloat(value).toFixed(2)}

      {{if commission}}              
          <td>${parseFloat(profit - commission).toFixed(2)}</td>   
      {{else}}
          <td>${profit}</td>
      {{/if}}
      

      【讨论】:

        【解决方案4】:

        你可以使用:

        var result = 2.855999999999;
        result = Math.round(result * 1000) / 1000;
        console.log(result ); //  ----> 2.856
        

        Working Demo

        【讨论】:

        • 为什么是Math.ceil()2.85511111111 仍将产生 2.856
        【解决方案5】:

        工作小提琴here

        你可以使用Math.round()

        var num = 2.855999999999
        num = Math.round(num * 1000) / 1000
        alert(num);
        

        对 .xx 等使用 100:D

        【讨论】:

          【解决方案6】:

          试试这个:

          parseFloat(${profit - commission}).toFixed(3);
          

          【讨论】:

            猜你喜欢
            • 2013-03-23
            • 1970-01-01
            • 1970-01-01
            • 2022-01-02
            • 2012-05-09
            • 1970-01-01
            • 2017-03-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多