Javascript Math Functions
The Javascript programming language has many math functions.
- parseFloat(string)
- Converts a string to a floating point number
- parseInt()
- Converts a string to an integer.
The Math Object's Properties
- .E
- Euler's constant
- .PI
- The value of Pi
The Math Object's Methods
The parameter is a number or a variable have a numeric value
- Math.abs(parameter)
- Returns the absolute value of the number passed to it.
- Math.floor(parameter)
- If the parameter provided is an integer, it will return that number otherwise it will round up to the next integer.
- Math.round(parameter)
- 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.
- Math.pow(parameter,power)
- Calculates the parameter to the specified power.
- Math.sqrt(parameter)
- Calculates and returns the squareroot of the parameter.
- Math.cos(parameter)
- Calculates and returns the cosine of the parameter.
- Math.sin(parameter)
- Calculates and returns the sine of the parameter.
- Math.tan(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.
variable_name.toFixed(number_of_decimal_places)
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.
variable_name.toPrecision(total_length_of_number)
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 .