The 20-time grand-slam champion has been struggling with a knee problem for the last three years and has decided now is the time to step away.
Federer will play in next week's Laver Cup in London, the Ryder Cup-style competition that was his brainchild, but will then leave the professional game.
Federer made the announcement via a letter posted on social media, which began: "To my tennis family and beyond. Of all the gifts that tennis has given me over the years, the greatest, without a doubt, has been the people I've met along the way: my friends, my competitors, and most of all the fans who give the sport its life.
"Today, I want to share some news with all of you.
"As many of you know, the past three years have presented me with challenges in the form of injuries and surgeries. I've worked hard to return to full competitive form.
"But I also know my body's capacities and limits, and its message to me lately has been clear. I am 41 years old.
"I have played more than 1,500 matches over 24 years. Tennis has treated me more generously than I ever would have dreamt, and now I must recognise when it is time to end my competitive career.
"The Laver Cup next week in London will be my final ATP event. I will play more tennis in the future, of course, but just not in Grand Slams or on the tour."