Brazil's bitterly divisive presidential election will go to a runoff on 30 October, as incumbent Jair Bolsonaro beat expectations to finish a relatively close second to frontrunner Luiz Inacio Lula da Silva.

The unexpectedly strong showing by Mr Bolsonaro yesterday dashed hopes for a quick resolution to the deeply polarised election in the world's fourth-largest democracy.

With 99.9% of electronic votes counted, Mr Lula had taken 48.4% of votes versus 43.2% for Mr Bolsonaro.

As neither got a majority of support, the race goes to a runoff vote at the end of the month.

The race has proven tighter than most surveys suggested, revitalising Mr Bolsonaro's campaign after he insisted that polls could not be trusted.

If he pulls off a comeback, it would break with a wave of victories for leftists across the region in recent years, including Mexico, Colombia, Argentina and Chile.

Adding to tensions in Brazil, Mr Bolsonaro has made baseless attacks on the integrity of Brazil's electronic voting system and suggested he may not concede if he loses.

Jair Bolsonaro suggested he may not concede if he loses

Last night, he sounded confident victory was within reach and avoided criticism of the voting system.

"I plan to make the right political alliances to win this election," he told journalists, pointing to significant advances his party made in Congress in the general election.

Mr Bolsonaro's right-wing allies won 19 of the 27 seats up for grabs in the Senate, and initial returns suggested a strong showing for his base in the lower house.

The strong showing for Mr Bolsonaro and his allies, which added to pressure on Mr Lula to tack to the centre, led bankers and analysts to expect a boost for Brazilian financial markets today after yesterday's surprising result.

Mr Lula put an optimistic spin on the result, saying he was looking forward to another month on the campaign trail and the chance to debate Mr Bolsonaro head-to-head.

Luiz Inacio Lula da Silva put an optimistic spin on the result

Inside his campaign, however, there was clear frustration that he had fallen short of the narrow majority forecast in some polls, along with weak results in state races outside of his party's traditional northeastern stronghold.

"There was a clear movement of votes in the southeast, beyond what the surveys and even the campaign managed to detect," a campaign source said on condition of anonymity because of the sensitivity of the matter.

Support for distant third- and fourth-place finishers also fell short of recent surveys, suggesting some of their backers may have shifted to Mr Bolsonaro when it came time to vote.

Centrist Senator Simone Tebet, who got 4% of votes, and centre-left former politician Ciro Gomes, who got 3%, both said last night they would announce decisions about endorsements in the coming days.