Ansari, who represents Surrey in English county cricket, said he wants to pursue other opportunities and is contemplating a career in law.
"After seven years as a professional cricketer and almost two decades in total playing the game, I have decided to bring my cricket career to an end," he said in a statement released by Surrey.
"This has been a very difficult decision to make and I have not made it lightly. It is... with great sadness that I say goodbye.
"Nevertheless, I have always been clear that when the time was right for me to move on I would, and that time has now come.
"While the timing may come as a surprise, I have always maintained that cricket was just one part of my life and that I have other ambitions that I want to fulfil.
"With that in mind, I am now exploring another career, potentially in law, and to achieve this I have to begin the process now."
Ansari, who made his Test debut against Bangladesh last October, played two Tests in India at the end of last year.
Image: Zafar Ansari
Photograph: Gareth Copley/Getty Images