NEW YORK (AP) — Walmart reported better-than-expected second-quarter results as more Americans looked to cut costs on groceries at the nation’s largest retailer in the face of surging inflation.

Those rising prices, however, meant that customers were cutting back on non-necessary purchases.

Walmart Inc. earned $5.15 billion, or $1.88 per share, or $1.77 excluding one-time costs and charges. That easily beat the $1.62 per share that Wall Street was looking for, according to FactSet.

It also topped last year’s profit of $4.27 billion.

Sales rose 8.4% to $152.86 billion, topping industry analyst projections.

Sales at stores open at least a year rose 6.5% as more shoppers turned to Walmart for groceries. That followed a 3% increase in the first quarter.

Online sale rose 12%, following a 1% increase in the previous quarter.

“We’re pleased to see more customers choosing Walmart during this inflationary period, and we’re working hard to support them as they prioritize their spending,” said CEO Doug McMillon.

McMillon, however, noted that strong sales were registered in groceries, which have lower margins, at a time when the company is cutting prices to get rid of excess inventory after a huge shift in how Americans spend money this year.

Like many big box retailers, Walmart benefited in the early days of the pandemic as shoppers splurged on food and other necessities, particularly online.

But shoppers are spending less on items that did well during the pandemic such as casual clothes and TVs when they focused on home activities. Surging inflation, which slowed last month but is still running at close to its highest level in four decades, is also presenting challenges for Walmart and other retailers as low-income shoppers cut back.

Late last month, Walmart spooked investors when it lowered its profit outlook for the second quarter and the full year, saying rising prices on food and gas are forcing shoppers to cut back on discretionary items, particularly clothing, that carry higher profit margins. The last time Walmart lowered its profit outlook mid-quarter was in October 2015.

But on Monday, it forecast a smaller profit drop for the fiscal year. It now expects consolidated adjusted operating income to decline 9% to 11%, an improvement from the company’s prior guidance of 11% to 13%.

Walmart Inc., based in Bentonville, Arkansas, is among the first major retailers to report quarterly results and is considered a crucial barometer of spending given its size and the breadth of its customer base.

Shares rose nearly 4% before the opening bell Tuesday.