1. Home
  2. Computing & Technology
  3. JavaScript

Calculator Tutorial

2. Convert to Javascript

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Getting Started

The second step in creating a calculator script now that we have the formula that the calculator is to use is to convert that formula into Javascript.

In the case of the Easter Calculator that I am building as we go through this example, the formula as written discards the fractional part after each division and so I need to add Math.floor functions around each division in the calculation. Apart from that the only other change I needed to make to the formula in my book (apart from correcting the code for the misprint) was to add var on the front of each declaration in order to let Javascript know that each is a new variable.

So here is the Easter Calculator Formula rewritten from my book into Javascript:

var a = year % 19;
var b = Math.floor(year/100);
var c = year % 100;
var d = Math.floor(b/4);
var e = b % 4;
var f = Math.floor((b+8) / 25);
var g = Math.floor((b-f+1) / 3);
var h = (19*a + b - d - g + 15) % 30;
var i = Math.floor(c/4);
var j = c % 4;
var k = (32 + 2*e + 2*i - h - j) % 7;
var m = Math.floor((a + 11*h + 22*k) / 451);
var month = Math.floor((h + k - 7*m + 114) / 31);
var day = ((h + k - 7*m +114) % 31) + 1;

Now that we have our formula (your's may not be anywhere near this complex) the next step is to test the formula to make sure that you haven't made any errors in setting it up.

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.