This paper presents a methodology to minimize the total cost of buying power from different energy producers including renewable energy generations particularly within the context of a microgrid. The proposed idea is primarily based on the controlled operation of a battery energy storage system (BESS) in the presence of practical system constraints coupled with our proposed cost optimization algorithm. The complex optimization problem with constraints has been solved using the well-known concept of dynamic programming. The methodology has been assessed using actual power and price data from six different power generation sites and cost reduction has been calculated for a number of BESSs by varying their energy and power capacities. Twofold benefits of the proposed methodology lie in minimizing the total cost along with the constraint-based efficient operation of the BESS. Simulation results depict that the given power demand at a particular region can be fulfilled properly at all times using a BESS and multiple power generation.