Most animals display multiple behavioral states and control the time allocation to each of their activity phases depending on their environment. Here we develop a new quantitative method to analyze Caenorhabditis elegans behavioral states. We show that the dwelling and roaming two-state behavior of C. elegans is tightly controlled by the concentration of food in the environment of the animal. Sensory perception through the amphid neurons is necessary to extend roaming phases while internal metabolic perception of food nutritional value is needed to induce dwelling. Our analysis also shows that the proportion of time spent in each state is modulated by past nutritional experiences of the animal. This two-state behavior is regulated through serotonin as well as insulin and TGF-beta signaling pathways. We propose a model where food nutritional value is assessed through internal metabolic signaling. Biogenic amines signaling could allow the worm to adapt to fast changes in the environment when peptide transcriptional pathways may mediate slower adaptive changes.