The Timely Measurements Assignment asks you to read the current date and time and return a value based on the circumference of a circle and the current hour. In order to do this you must be able to extract and store the hour in a variable.
To start, you need to capture the current date and time and store it into a variable that you can use to then extract the hours. Use the Date() method to do this. var currentDate = new Date();
. This will allow you to use Date() methods on the currentDate
variable. Saving the hours is now just a matter of using the getHours() method. var hour = currentDate.getHours();
For more check out: https://www.w3schools.com/js/js_dates.asp.
Once the hour is stored, you will calculate the radius using r = (2π)/C. The value of π is stored in the Math Object as Math.PI. When written in javascript your equation will read: circumference = (2 * Math.PI()) * radius;
The Timely Measurements Assignment also asks you to round your output to a certain number of decimals. There are many ways to round using javascript, here I'll discuss one way by hacking the Math.round() method.
Math.round()
- rounds to the nearest integer (if the decimal is 0.5 or greater it rounds up, otherwise it rounds down.)Math.ceil()
- rounds up to the next integer.Math.floor()
- rounds down.Let's do some examples:
var x = 2.71828182845;
Math.round(x);
Math.ceil(x);
Math.floor(x);
The outputs are 3, 3, and 2 respectively. This type of rounding can be useful sometimes, but often we want to round to a specific number of decimal places. We are going to hack the Math.round() method by playing with decimal places. Remember back to math class where you learned that by multiplying or dividing by 10 you can move the decimal place. This how scientific notation works. Multiply by 10 to move the decimal once to the right, and divide by 10 or (101) to move once to the left. Multiply or divide by 100 or (102) to move 2 places, 1000 or (103)for 3. We can generalize by saying multiply or divide by 10n to move the decimal n places. To move the decimal back, do the opposite function with the same number. ex. if you multiply by 10, then divide by 10 to move the decimal back. Let's use this knowledge with example above to round x to different decimal places.
var x = 2.71828182845;
//round to 2 places
Math.round((x * 10) / 10);
//ceil to 3 places
Math.ciel((x * 100) / 100);
//floor to 4 places
Math.floor((x * 1000) / 1000);
Now the outputs are 2.72, 2.718 and 2.7182. Use this method to round your outputs to specific decimal places.
Write a function that rounds to a specific number of decimal places.