开发者

can any one suggest a good math function in javascript to round integer?

开发者 https://www.devze.com 2023-03-10 02:14 出处:网络
i have to round the value from 2.3456789 开发者_JAVA技巧to 2.345 . After . there must be three number only remaining should be removed Use Math.round().

i have to round the value from 2.3456789 开发者_JAVA技巧to 2.345 .

After . there must be three number only remaining should be removed


Use Math.round().

This will round to 3 decimal places.

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

In fact, the formula to round any number to x decimal points is:

1) Multiple the original number by 10^x (10 to the power of x).
2) Apply Math.round() to the result.
3) Divide result by 10^x.


Javascript 1.5+ introduced Number.toFixed(n) and Number.toPrecision(n) - pick one depending on what you need.

Number.toFixed() lets you specify the number of digits after the decimal point (padded if necessary).

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

Number.toPrecision() lets you specify the number of significant figures.

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


There is value.toFixed(3), but that will round up to 2.346.

You could just parseInt(value * 1000) / 1000 if you really don't want to round.

You may need to ensure value is a number first:

value = new Number(value)

Now if value is user input, it's possible that it might now be NaN (Not a Number).

You can't do if(value == NaN) to check, NaN is never equal to anything (not even itself), you must use the isNaN(value) function.


Try Math.floor(2.3456789 * 1000) / 100. This might result in floating-point errors, so it might be a better idea to just do it via string functions

var parts = String(2.3456789).split(".");
var out = parts[0] + "." + parts[1].substring(0, 3);

Of course, the second method may choke on numbers with exponents.


Use this function to round the number

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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消