JavaScript数学,在Jquery模板中四舍五入到小数点后两位

JavaScript math, round to two decimal places in Jquery template

本文关键字:小数点 两位 四舍五入 数学 Jquery JavaScript      更新时间:2023-09-26

我有一些代码

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

profit = 5;

commission = 2.145

result = 2.855999999999

我需要2.856

请帮帮我

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

直接使用toFixed(3),它将选择点值后面的3位数字

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

OP: 2.856

演示

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);

在jQuery模板中使用

parseFloat应该在${}

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

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

您可以使用:

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

在这里工作

可以使用Math.round()

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

试试这个:

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