Simple Math calculations
The built-in Math object includes mathematical constants and functions. You do not need to create the Math object before using it.
|function||Meaning (returns ..)|
|abs(x)||the absolute value of x|
|ceil(x)||the nearest integer greater than or equal to x|
|cos(x)||the cosine of x|
|exp(x)||the value of E raised to the power of x|
|floor(x)||the nearest integer less than or equal to x|
|log(x)||natural log of x|
|max(x,y)||the number with the highest value of x and y|
|min(x,y)||the number with the lowest value of x and y|
|pow(x,y)||the value of the number x raised to the power of y|
|random()||a random number between 0 and 1|
|round(x)||x rounded to the nearest integer|
|sin(x)||the sine of x|
|sqrt(x)||the square root of x|
|tan(x)||the tangent of x|
Math example 1 (js6_01)
Note:Use refresh to see the random number change.
Math example 2 Currency converter (js6_02)
- ParseFloat: Determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.
- this.value is shorthand that says use "this" objects value
- You need to click "off" the number for the currency to be shown.
An issue that arises is when a number is expected in a textBox but the user does not enter one. In this case parseFloat will return Not a Number (NaN) and the arithmetic will not evaluate.
This can be fixed by adding an if statement straight after the number is converted, for example:
Activity: Simple calculator
- Create two text boxes (number 1 and Number 2) and four buttons +,*,*,/ plus an Answer text box
- When a user enters two numbers they can click the appropriate button and the total is placed in the total box