toFixed vs padEnd

 

  • toFixed(2) → always returns exactly 2 decimal places and rounds (e.g. 1.235 -> "1.24", 1 -> "1.00").
  • Your current formatNumberWithDecimal → pads to at least 2 decimals but preserves extra digits (e.g. 1.235 -> "1.235", 1 -> "1.00").


//format number with decimal places
export function formatNumberWithDecimal(num: number): string {
  const [int, decimal] = num.toString().split('.');
  return decimal ? `${int}.${decimal.padEnd(2, '0')}` : `${int}.00`;
}

Comments

Popular posts from this blog

new Promise((resolve) => setTimeout(resolve, ms))

min-h-screen in Tailwind CSS

Ecommerce with JS