Number to fixed-point notation without trailing zeros

Angelos Chalaris · JavaScript, Math, String · May 10, 2022

Formats a number using fixed-point notation, if it has decimals.

  • Use Number.prototype.toFixed() to convert the number to a fixed-point notation string.
  • Use Number.parseFloat() to convert the fixed-point notation string to a number, removing trailing zeros.
  • Use a template literal to convert the number to a string.
const toOptionalFixed = (num, digits) =>
  `${Number.parseFloat(num.toFixed(digits))}`;
toOptionalFixed(1, 2); // '1'
toOptionalFixed(1.001, 2); // '1'
toOptionalFixed(1.500, 2); // '1.5'

Recommended snippets

  • Number to decimal mark

    JavaScript, Math

    Converts a number to a decimal mark formatted string.

  • Takes a number and returns it in the specified currency formatting.

  • Luhn check

    JavaScript, Math

    Implements the Luhn Algorithm, used to validate a variety of identification numbers.