Assume unformatted floats need rounding

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the user-input-and-output category.

Last Updated: 2021-05-16

I drafted some UI code that included the following function:

export function toPercent(ratioAmount) {
  const percentAmount = ratioAmount * 100
  return `${percentAmount} %`
}

// USAGE
toPercent(0.07)

Sure enough, thanks to floating point calculations, this printed the following UI-busting ugliness:

7.000000000000001 %

yep, that's ugly...

Here's the fix - rounding just before display to the user:

export function toPercent(ratioAmount) {
  const percentAmount = ratioAmount * 100
  return `${percentAmount.toFixed(2)} %`
}