Allah tells in the Quran why Muslims have to fast – “O you who have believed, decreed upon you is fasting as it was decreed upon those before you that you may become righteous” (Quran 2:183). Taqwa is an arabic word and when it is used in the context of the Quran, it means consciousness or fear of Allah. So Allah tells us that the reason Muslims have to fast is so that they can become more righteous and to achieve this taqwa of Allah. When some Muslims are asked this question, they might say that they fast because it cleanses out the body, so that they can feel and sympathize with the poor, etc. Although these are some extra benefits of fasting, this is not the main reason that Allah has prescribed fasting for Muslims.
How come Muslims have to fast specifically in the month of Ramadan. Allah answers this question a couple of verses later – “Ramaḍan is the month in which the Quran was revealed as a guide for humanity with clear proofs of guidance and the standard ˹to distinguish between right and wrong˺. So whoever is present this month, let them fast. But whoever is ill or on a journey, then ˹let them fast˺ an equal number of days ˹after Ramaḍan˺. Allah intends ease for you, not hardship, so that you may complete the prescribed period and proclaim the greatness of Allah for guiding you, and perhaps you will be grateful” (Quran 2:185).
And Allah knows best.