//PROCESS: Basic math

True fact: Computers are good at math!

Regular
math
Javascript
math
On the keyboard Code sample
3+2 3 + 2 + is shift=
3−2 3 - 2 -
3×2 3 * 2 * is shift8
3•2 3 * 2 * is shift8
3⁄2 3 / 2 /
3÷2 3 / 2 /
Math.pow( 3, 2 )
Math.pow( 2, 3 )
3√2 3 * Math.sqrt( 2 )
∛2 Math.pow( 2, (1 / 3) )
sin(3°) Math.sin( 3 )
cos(3°) Math.cos( 3 )
tan(3°) Math.tan( 3 )
π Math.PI
parseInt( "35 degrees" )

Cleaning your data with parseInt()

Often the data that you read in your program is dirty — particularly when you are converting between datatypes, like converting strings to numbers.

This is where parseInt() comes in handy. parseInt() looks at a string, and extracts the first number that it sees.

For example, parseInt( "1855 Trollope Street" ) will return the number 1855. It is a real problem-solver!

Common mistakes

Learn more

Code example

...is made with the following code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>drapak.ca - Area of a circle</title>
        <meta name="description" content="This script calculates the area of a circle given a radius">
        <meta name="author" content="Dave Drapak">
        <!--
            Change log:
                27. Sept 2015   - created
                3. March 2017   - reworked to move script to the end
        -->
    </head>

    <body>
        <h1>Calculate the area of a circle</h1>
        
        <p>
            What is radius of the circle?
            
            <input id="radiusID" value="5">
                
            <button id="buttonID">
                Calculate the area!
            </button>
        </p>
        
        <p>The area is: <strong id="outputID"></strong></p>

        <script>
            // read the input and output the 
            var mainProcedure = function () {
                // get the radius from the input line
                var radius  = document.getElementById('radiusID').value;

                // calculate the area
                var area    = Math.PI * ( Math.pow( radius, 2) );
                
                // output the answer
                document.getElementById('outputID').innerHTML   = area;
            }
            
            //INPUT: attach the change event to radiusID
            document.getElementById('radiusID').onchange    = mainProcedure;

            //INPUT: attach the click event to buttonID
            document.getElementById('buttonID').onclick     = mainProcedure;
        </script>
    </body>
</html>