Walter Sparrow (Jim Carrey) wrote the book "The Number 23" thirteen years ago. He was obsessed with the number since it was the only thing he saw after his dad committed suicide. The obsession eventually resulted in the murder of his college girlfriend Laura Tollins (Rhona Mitra), who had left him for one of her professors (who was subsequently accused for the murder).
Walter started writing the book as a suicide note, but it turned into a novel fuelled both by his obsession and love for detective stories. The book only included chapters 1-22, while chapter 23, which featured Walter explaining his obsession and confessing his crimes, was written on the wall of the hotel room he was staying in. After finishing writing the book, Walter attempted suicide and was admitted into a mental hospital unable to remember what he'd done. The book was taken and published by one of the doctors in the hospital, who subsequently inherited the obsession (and who later committed suicide when found by Walter). Just as he was leaving the hospital, Walter met his wife Agatha (Virginia Madsen) and began his new life.
After discovering he is the true author of the book, Walter once again becomes suicidal. Agatha tries to convince him it was all in the past, but Walter runs outside right in front of a bus. However, after seeing his son in the street, he realizes suicide is the easy way out and he jumps out of the way of the bus. He later turns himself in for the murder of Laura and shares a moment with his family in jail.
Walter narrates that he will eventually be paroled and he and his family will one day go on with their lives again together.
Thanks Vigz and Sean!