Jair Bolsonaro, a former army captain, gained 46% of the vote — falling just short of securing enough support to avoid a second-round runoff against his left-wing opponent.
He needed more than 50% support to win outright.
His rival, former Sao Paulo mayor Fernando Haddad, won only 29%, according to figures from Brazil’s superior electoral tribunal with 99.9% of the vote counted.
Mr Bolsonaro’s win was predicted in the polls but the extent of his victory came as a surprise.
He was competing against those with more money behind them, greater media exposure and more traditional political support.
The candidate from the small Social and Liberal Party used Twitter and Facebook to reach voters and to capitalise on the country’s anger in the wake of a massive corruption scandal.
Mr Bolsonaro told his audience that he was their only option to end the corruption, crime and economic stagnation gripping Brazil.
«I voted against thievery and corruption,» said Mariana Prado, a 54-year-old human resources expert.
«I know that everyone promises to end these two things, but I feel Bolsonaro is the only one can help end my anxieties.»
The 63-year-old also advocates loosening gun ownership laws to enable citizens to defend themselves as well as allowing police to use more force in a Brazil that he says is in a state of turmoil.
His poll numbers jumped by around 15% after he wasstabbed in the stomach during a campaign eventin September.
He had to undergo emergency surgery and his son reported the politician had suffered severe blood loss and arrived at the hospital «almost dead».
He was unable to campaign in person or participate in debates as he underwent surgeries during a three-week hospital stay — instead he used social media to communicate with the electorate.
The Workers’ Party has been at the centre of the corruption investigation and has struggled to shake off criticism under its new leader Mr Haddad.
He promised to roll back the economic reforms that he says eroded workers’ rights, increase investment in social programmes and bring back the boom years Brazil experienced under his mentor,Luiz Inacio Lula da Silva.
Mr da Silva led initial polls by a wide margin, but was banned from running after a corruption conviction.
Although the candidates stand on opposite sides of the political spectrum, both threaded nostalgic sentiments throughout their campaigns with frequent references to «traditional» Brazilian life.