The first fingers and toes evolved from earlier fish fins about 400 million years ago. During the Devonian period, the oceans were very shallow, and some fish evolved to be able to push themselves out of the water to breathe the air. For this, they needed stronger fins that they could push up with. At first these fish had eight fingers and eight toes on each leg.
Probably the way they got the fingers and toes was that a few fish sperm or eggs had genetic mutations of their DNA during meiosis. Their mutation left their Hox genes turned on a little bit longer, so their fins grew longer and branched more.
Later these long-finned fish learned to use their fins to walk around in the shallow puddles which were hard to swim in. Fingers and toes helped them to balance as they were walking around in the water.
When the first lungfish started to walk on land, all those fingers and toes just got in the way and made it hard to walk, so they gradually evolved to lose those toes and fingers until they got down to five, which was more useful. That’s what most humans have. Other mammals lost even more toes and fingers, and developed hooves or paws instead.