In the last decade, due to the high penetration of renewable energy sources (RES) including wind and solar energy sources in the microgrid (MG), the importance of the battery energy storage (BES) has increased remarkably. The BES has many benefits in MG-based applications such as short-term power supply, power quality enhancement, facilitation of RES integration, ancillary services, and transaction benefits. In this study, a cost-based formula to calculate the optimal capacity of BES in MG is proposed. Also, some limitations, such as the capacity of generator in distribution generation (DG), BES power, capacity, charge/discharge efficiency, reserve storage, and satisfaction of demand points, must be considered. The proposed problem is a complex optimization; its complication increases due to the mentioned limitations. Consequently, a robust and powerful optimization algorithm is essential to solve the problem. In this study, an Artificial Flora (AF) Algorithm is used to perform load distribution between sources with the minimized cost. The operation of this method is examined by a low-voltage grid-connected MG, that the optimum BES size is professionally determined.