I want to modify CriticalMessage's response a little. To be an earned run, the batter must have become a runner and later scored through "errorless" play. Per the MLB rules for official scorers, the scorer should "reconstruct the inning without the errors (which exclude catcher's interference) and passed balls ... in determining which bases would have been reached by runners had there been errorless play" (Official Rules 10.6).
For example, the first batter reaches first base by an error. The second batter hits a double and the first batter advances to third. The third batter hits a double and both of the first and second batters score. The pitcher will be charged with one earned run and two runs allowed. The one earned run will count in the calculation of ERA.
The Official Rules has a number of examples which describe a variety of situations in determining which runs are earned (ER) and which are simply runs allowed (R). I'll include the link below.
That was no modification other than just more detail on what I had already described for I did include the description (not by errors)... So where was your modification to my description for providing more details of the same event is not modifying.
The previous descriptions are all correct, but here's a "formula" that you asked about:
Take the amount of earned runs allowed by a pitcher and divide that by innings pitched. Keep in mind that some people write fractions of innings as decimals (for example, 6 1/3 innings is sometimes written as 6.1). Then take the number you get and multiply that by 9. This will give you a pitchers exact ERA over any period of time you desire to know.