30秒学会 JavaScript 片段 · 2022年7月31日

30秒学会 JavaScript 片段 – Number to fixed-point notation without trailing zeros

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'

翻译自:https://www.30secondsofcode.org/js/s/number-to-optional-fixed