std: fix an infinite loop in num::ToPrimitive and add tests