There are five fingers on a person’s hands and legs because exactly so many fingers were in the monkeys from which we descended, and the monkeys inherited five-fingered limbs from their ancestors, and so on, down to the ancient amphibians that lived more than 300 million years ago. Apparently, the common ancestor of all modern terrestrial vertebrates had five-fingered limbs. In other words, a five-fingered limb is a primitive, initial limb structure for all terrestrial vertebrates. In most species, including humans, this structure has survived to this day.
Some vertebrates experienced a decrease in the number of fingers or even their complete loss, sometimes together with the limbs themselves. Usually, this happened in those animals, which for some reason, some fingers began to interfere, became "superfluous". For example, the ancestors of horses on the middle finger developed a large hoof, the finger itself greatly increased, and the remaining fingers became unnecessary, they only interfered with the growth of the middle finger, and gradually disappeared. Apparently, the ancestors of a person did not experience such situations that some fingers became “superfluous". Therefore, they are all preserved.
The question, therefore, boils down to why the common ancestor of all modern terrestrial vertebrates had a five-fingered limb. Scientists today believe that there were no special reasons for this. The five-fingered limb does not have any fundamental structural advantages in comparison with the four- or six-fingered. Apparently, five-fingered was fixed in the evolution of vertebrates purely by accident.
Among the oldest fossils of tetrapods, paleontologists found that there were forms with a different number of fingers: for example, the ichthyostegs had seven toes on their hind legs (the forefoots were not preserved), the acanthostegs had eight toes on their forepaws and at least the same number on their hind legs. The legs came from the fins of the fish, the fingers from the rays of these fins, and the number of fin rays from those fish from which the terrestrial vertebrates originated was variable.
Apparently, in the oldest terrestrial tetrapods, the number of toes also varied. It happened by chance that it was the five-fingered forms that gave rise to the whole variety of modern four-legged animals, and animals with a different number of fingers died out. But they died out, most likely, not because they had an unsuccessful number of fingers, but for some completely different reasons, in connection with some other, more significant “defects” of their structure. In principle, it could well be “lucky” not with five-fingered, but, say, with seven-fingered ancient amphibians. And then, perhaps, people would now have seven fingers in their hands.