任何人都可以在javascript中建议一个好的数学函数来舍入整数?

时间:2011-06-02 07:09:29

标签: javascript math

我必须将值从2.3456789四舍五入到2.345

.之后,必须删除剩余的三个号码

5 个答案:

答案 0 :(得分:3)

使用Math.round()

这将舍入到小数点后3位。

var result=Math.round(2.3456789*1000)/1000  //returns 2.345  

事实上,将任意数字舍入到x小数点的公式为:

1)10^x (10 to the power of x)多个原始数字 2)将Math.round()应用于结果 3)将结果除以10^x

答案 1 :(得分:3)

Javascript 1.5+引入 Number.toFixed(n) Number.toPrecision(n) - 根据您的需要选择一个。

Number.toFixed()允许您指定小数点后的位数(必要时填充)。

(2.3456789).toFixed(3) = "2.346"
(3).toFixed(3) = "3.000"

Number.toPrecision()可让您指定有效数字的数量。

(2.3456789).toPrecision(4) = "2.346"

答案 2 :(得分:2)

value.toFixed(3),但这将会达到2.346。

如果你真的不想回合,你可以parseInt(value * 1000) / 1000

您可能需要先确保数值为数字:

value = new Number(value)

现在,如果value是用户输入,则现在可能是NaN(非数字)。

你不能if(value == NaN)检查,NaN永远不等于任何东西(甚至不是自己),你必须使用isNaN(value)功能。

答案 3 :(得分:1)

试试Math.floor(2.3456789 * 1000) / 100。这可能会导致浮点错误,因此通过字符串函数

执行此操作可能更好
var parts = String(2.3456789).split(".");
var out = parts[0] + "." + parts[1].substring(0, 3);

当然,第二种方法可能会用指数阻塞数字。

答案 4 :(得分:0)

使用此功能对数字进行四舍五入

// Arguments: number to round, number of decimal places

function roundNumber(rnum, rlength) {

  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);

  retrurn parseFloat(newnumber); // Output the result to the form field (change for your purposes)

}