Javascript Math Functions

The Javascript programming language has many math functions.

Converts a string to a floating point number
Converts a string to an integer.

The Math Object's Properties

Euler's constant
The value of Pi

The Math Object's Methods

The parameter is a number or a variable have a numeric value

Returns the absolute value of the number passed to it.
If the parameter provided is an integer, it will return that number otherwise it will round up to the next integer.
Rounds a number to the nearest integer.
Math.max(First Parameter ,Second Parameter)
Returns the greater of two numbers.
Math.min(First Number ,Second Number)
Returns the least of two numbers.
Calculates the parameter to the specified power.
Calculates and returns the squareroot of the parameter.
Calculates and returns the cosine of the parameter.
Calculates and returns the sine of the parameter.
Calculates and returns the tangent of the parameter.

function rndresult(rawresult,rnddigits)
//Function to round numbers to a specified number of decimal places. //round results and return value
var realresult = rawresult;

var decimalpl = rnddigits;
//take rounding digits and make decimalpl = 10 to the (rounding digits) power
var decimalpl = (Math.pow(10,decimalpl));
// Math.round will only round to nearest integer multiply by 10 to the number of decimal places.
//Round the result and divide by 10 to the number of decimal places.
realresult = (Math.round(realresult * decimalpl))/decimalpl ;

var roundedresult = parseFloat(realresult); // make sure number is delivered back to multiply()

return(roundedresult)// return rounded number.

Rounding Real Numbers with Javascript 1.5 +

The toFixed and toPrecision Methods were first introduced in Javascript 1.5. Previous versions of javascript had no math function to round real or floating point numbers only integers, so that a programmer had to write code to cope with this situation. The toFixed method will round a numeric variable to the number of decimal places specified in the parenthesis of the statement.
The toPrecision method on the otherhand will deliver a number which has a total length equal to the number in the parenthesis of the statement.
Below is an example showing the difference in the two methods.

var testnumber = 125.02586;
var fixed1 = testnumber.toFixed(4);
var precise1 = testnumber.toPrecision(4);

The result will be fixed1 = 125.0259 and precise1= 125.0 .

Site Index