Files
30-seconds-of-code/snippets/js/s/number-to-optional-fixed.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

742 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Number to fixed-point notation without trailing zeros snippet javascript
math
string
chalarangelo white-chapel 2022-05-10T05:00:00-04:00

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'