在 JavaScript 中将十进制数表示为 C 中的"%g"格式



我有一个生成为有限小数的数字:

var x = k * Math.pow(10,p)

带有 k 和 p 整数。有没有一种简单的方法可以将其转换为精确的字符串表示形式?

如果我使用隐式字符串转换,我会得到丑陋的结果:

""+ 7*Math.pow(10,-1)

"0.7000000000000001"

我尝试使用 .toFixed 和 .toPrecision,但很难根据 k 和 p 找到要使用的正确精度。有没有办法获得C语言的旧"%g"格式?也许我应该求助于外部图书馆?

可以使用

math.js库中的math.format

math.format(7 * Math.pow(10, -1), {precision: 14});

"0.7"
你可以

像这样创建自己的floor函数,选项accuracy

  function fixRound(number, accuracy) {
      return ""+Math.floor(number * (accuracy || 1)) / accuracy || 1;
  }
  let num = 7 * Math.pow(10, -1);
  console.log(fixRound(num, 1000))