To prevent sleeping villagers from floating away, make sure entities such as cats, golems, and other players cannot touch the villager's bed while the villager is sleeping. (Unfortunately, villagers seem to float away for no reason in some cases, so this may not work 100% of the time.)
To bring a villager back to its bed after it has floated away, try one of the following workarounds. Note that these are temporary solutions; if a returned villager is touched again after you bring it back, it will float away again.
The first group works by forcing the villager to get out of bed: (The bug only affects villagers that are in bed/lying down.)
- Wait until the villager wakes up in the morning.
- Break the bed.
- Sleep in the bed, displacing the villager.
- Open the villager's trading UI.
- Attack the villager (note that this will reduce your popularity in the village and get the golems angry at you if there are any)
The next group works by making the game refresh its information about the villager. If multiple players are in the village, all players must do this at the same time:
- Move far away from the bed, then return. 100 blocks is usually enough, but you might have to go farther.
- Go through a Nether portal, then return. On some platforms, you may need to wait a few minutes before returning.
This last method is the most reliable, but also the most disruptive:
- Save and reload the world. In a multiplayer world, all players must exit. On Realms, close the Realm and wait 15 minutes before reopening and rejoining.