"How many levels should I spend to enchant this sword?"

The answer is almost always: all of them.

Why? Well, it's a result of the way experience levels interact with enchanting in Minecraft.

First, a bit of background on the XP and leveling system: In general, getting from level n to level (n + 1) takes (n + 2) * 7 / 2 (rounded down) experience points. (Note that one orb is not necessarily one point.) So, leveling from level 0 to level 1 takes 7 points, and leveling from 4 to 5 takes 21 points.

Now, a level 2 enchantment always costs you two levels, no matter what level you are currently at. So, if you buy a level 2 enchantment when you are at level 2, you spend 7 + 10 = 17 points on that enchantment, since the enchantment takes levels 1 and 2 away from you. But if you buy the exact same enchantment when you're at level 10, it will instead take away levels 9 and 10, for a total cost of 35 + 38 = 73. So now you have paid over 4 times as much XP, for the exact same enchantment!

This means you should spend all of your levels, every time you perform an enchantment. Anything less is a waste of XP.

The exception to this rule is if you are trying to obtain a specific enchantment using the smallest number of items. If this is your goal, you should always spend the exact number of levels listed on the strategy table. In this case, you should enchant as soon as possible after reaching the appropriate level. Even partial levels beyond the goal are mostly wasted, so you should try to avoid obtaining extra XP once you are at the goal level.