使用.toFixed()仅在需要时显示3个小数

时间:2018-07-19 08:59:40

标签: javascript

如何将.toFixed()用于此结果。

number     display
------     -------
1          1
1.23       1.23
1.23456    1.235

我一直在使用.toFixed(3)。但这是显示。

number     display
------     -------
1          1.000
1.23       1.230
1.23456    1.235

4 个答案:

答案 0 :(得分:1)

您可以尝试使用:

Math.round(yournum * 1000) / 1000

或者您可以尝试:

+(Math.round(num + "e+3")  + "e-3")

答案 1 :(得分:1)

您可以删除不需要的零或点。

@SpringBootApplication

答案 2 :(得分:1)

另一种选择是使用NumberFormat而不是>>> variable2 = globals()[input()] variable1 >>> variable2 10

toFixed

答案 3 :(得分:1)

您可以创建一个简单的函数来检查小数位数,然后仅在toFixed达到3时运行。

类似的事情会起作用。

这是一个片段

let dP = n => {
  if (n.toString().includes('.')) return n.toString().split('.')[1].length
};

[1, 1.23, 1.23456].forEach(n => {
  console.log(dP(n) >= 3 ? n.toFixed(3) : n)
})

我希望这对您有帮助