The leading minus sign in the gain formula is a double negative, so to speak. It serves to render gains positive and losses negative. Long term and short term gains For income tax purposes gains must be separated into long and short term. First in first out always applies here. The loss on the number of shares purchased is disallowed for tax purposes, not allowed to cancel gains.
Many bond funds distribute dividends monthly.
Any partial redemption at a loss from such a fund automatically incurs a wash sale. Here is a simple example. A total of 623.441 shares were sold at a loss. Due to the monthly reinvestment of dividends, however, 26.733 shares were purchased within 30 days of the sale. The loss on this number of shares is disallowed for tax purposes.