The hardline mayor of Tehran is to face a veteran former president in a run-off for Iran's presidency, after a surprise result in Friday's first round.
Mr Ahmadinejad had trailed far behind for much of the race
The second round pits conservative Mahmoud Ahmadinejad against pragmatic cleric Akbar Hashemi Rafsanjani, who led Iran for eight years until 1997.
Mr Rafsanjani had been expected to do well, but few predicted Mr Ahmadinejad would be his rival, correspondents say.
No Iranian presidential election has gone to a second round before.
The second round will take place on Friday, a week after the original poll.
Mr Ahmadinejad's showing was so unexpected even his own campaign team had not prepared a podium where he could react to the announcement.
He apparently had strong support among the devout poor who live in the capital's suburbs.
Akbar Hashemi Rafsanjani - 21%
Mahmoud Ahmadinejad - 19.5%
Mehdi Karroubi - 17.3%
Souce: Iranian interior ministry
"I am the people's candidate," he declared after workers quickly cobbled together a podium so he could hold a news conference.
Mehdi Karroubi, a reformist cleric and former parliamentary speaker whom few had tipped as a major contender in the race, came in third, close behind Mr Ahmadinejad.
As the results came in, he alleged they had been tampered with.
"There has been bizarre interference. Money has changed hands," he told reporters.
He called for an investigation.
The reformists' standard-bearer Mostafa Moin came in fifth place.
According to the interior ministry, some 62% of the electorate took part in the polls, despite boycott calls from some reformist groups.
Iranian authorities had hoped for a high turn-out to fend off foreign criticism that the elections were unfair.
The BBC's Frances Harrison in Iran said the turn-out was very respectable - and could be even higher in the second round.
Voters would want to choose between two men with very different policies, she said.
Mr Rafsanjani, 70, has close ties to the clerical elite, but he has adopted a more liberal message for his campaign, promising better relations with Western nations, including the US.
Mr Ahmadinejad, 49, is a former Revolutionary Guard who became mayor of Tehran in 2003 after reformists had run the capital in the 1990s.
He is a much-less known figure nationally and internationally, and has close ties to the regime, our correspondent says.
Voting was extended three times on Friday and finally ended at 2300 (1830 GMT), four hours later than planned.
Dissidents and students had called for a boycott in protest at the barring of women and many reformists from the race.
Iranians were choosing their president from a field of seven, after some 1,000 potential candidates were disqualified from the race by the clergy.
Some 47 million people, many of them under 30, were eligible to vote.
Ultimate power in Iran rests with clerical bodies and the unelected supreme leader, Ayatollah Ali Khamenei.