Shared and improved formatting function