Context. Methanol and its precursor formaldehyde are among the most studied organic molecules in the interstellar medium and are abundant in the gaseous and solid phases. We recently developed a model to simulate CO hydrogenation via H atoms on interstellar ice surfaces, the most important interstellar route to H 2 CO and CH 3 OH, under laboratory conditions. Aims. We extend this model to simulate the formation of both organic species under interstellar conditions, including freeze-out from the gas and hydrogenation on surfaces. Our aim is to compare calculated abundance ratios with observed values and with the results of prior models. Methods. Our model utilises the continuous-time, random-walk Monte Carlo method, which -unlike other approaches -is able to simulate microscopic grain-surface chemistry over the long timescales in interstellar space, including the layering of ices during freeze-out. Results. Simulations under different conditions, including density and temperature, have been performed. We find that H 2 CO and CH 3 OH form efficiently in cold dense cores or the cold outer envelopes of young stellar objects. The grain mantle is found to have a layered structure with CH 3 OH on top. The species CO and H 2 CO are found to exist predominantly in the lower layers of ice mantles where they are not available for hydrogenation at late times. This finding is in contrast with previous gas-grain models, which do not take into account the layering of the ice. Some of our results can be reproduced by a simple quasi-steady-state analytical model that focuses on the outer layer. Conclusions. Observational solid H 2 CO/CH 3 OH and CO/CH 3 OH abundance ratios in the outer envelopes of an assortment of young stellar objects agree reasonably well with our model results, which also suggest that the large range in CH 3 OH/H 2 O observed abundance ratios is due to variations in the evolutionary stages. Finally, we conclude that the limited chemical network used here for surface reactions apparently does not alter the overall conclusions.