user737767
user737767

Reputation: 1024

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

i have to round the value from 2.3456789 to 2.345 .

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

Upvotes: 2

Views: 201

Answers (5)

Amit
Amit

Reputation: 109

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)

}

Upvotes: 0

Andy
Andy

Reputation: 2214

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"

Upvotes: 3

Lee Kowalkowski
Lee Kowalkowski

Reputation: 11751

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.

Upvotes: 2

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46415

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.

Upvotes: 3

user193476
user193476

Reputation:

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.

Upvotes: 1

Related Questions