Where the story is told
This story is not in the Quran. It is an authentic hadith that the Prophet ﷺ narrated about a man from earlier times. It is found in Sahih al-Bukhari 3470 and in Sahih Muslim 2766, both through Abu Sa'id al-Khudri.
Sahih al-Bukhari says he was among the Children of Israel. Sahih Muslim says he was among those who lived before us. The two narrations differ a little in wording, and Sahih Muslim gives more details. The story below follows both.