Perfectly, as in a dress fits correctly. A solution or bit of advice that is exactly what was wanted. Why ‘T’ is used is unknown but it means the right and proper thing. Something that is fitting, appropriate. (Compare to Hit the nail on the head.)
“That dress fits you to a T.”