This paper describes a new measurement of the flux ratio of positive and negative muons from cosmic-ray interactions in the atmosphere, using data collected by the CMS detector at ground level and in the underground experimental cavern. The excellent performance of the CMS detector allowed detection of muons in the momentum range from 3 GeV to 1 TeV. For muon momenta below 100 GeV the flux ratio is measured to be a constant $1.2766 pm 0.0032(stat) pm 0.0032(syst)$, the most precise measurement to date. At higher momenta an increase in the charge asymmetry is observed, in agreement with models of muon production in cosmic-ray showers and compatible with previous measurements by deep-underground experiments.