The Swiss will stand behind Novak Djokovic on the ATP list after winning the 74th title of his career.
Federer went level with Rafael Nadal, who will slip to three in the world, on 20 career titles at the Masters 1000 level, with both men holding the record.
The 30-year-old Federer was playing in his 104th ATP final and won his fourth title of the season.
Earlier, Serena Williams crushed world No.1 Victoria Azarenka 6-1 6-3 to win the ladies crown in Madrid and make a return to the number six ranking.
The American has now won back-to-back WTA clay titles, after claiming Charleston in the US a month ago, and hammered home her credentials as a serious threat at the French Open which begins in two weeks.
“I’m so happy to win this title,” said Williams, who now owns five trophies on clay. “I really felt good on the court.”
The bruising victory lifted the American to a 7-1 record over Azarenka, who won her only match in the series in Miami, 2009.
“I just want to play consistent and that’s what I’ve done the last few weeks,” Williams said. “I belong on a court. That’s where I do what I do best and feel amazing.”
Williams feels that her new number six ranking should be only a stepping stone to her ultimate goal.
“I don’t play to number two, no one does — we are all playing to be the best. Number one is my ultimate goal.”
The American swept to a double-break in 12 minutes at the start, secured the set in 26 minutes on a double-fault and continued the demolition in the second to complete the win in 64 minutes.