【问题标题】:How to prevent very small numbers from being converted to scientific notation?如何防止将非常小的数字转换为科学计数法?
【发布时间】:2018-06-04 05:27:10
【问题描述】:

我必须使用非常小的数字:

var x = 0.00000006;

当我运行 console.log(x) 时,它显示:

6e-8

我不希望它显示 6e-8 ,我希望它显示 0.00000006

稍后我需要将其绘制在图表上,因此无法将其转换为字符串。 如何在不将其转换为字符串或科学记数法的情况下保持较小的数字?

【问题讨论】:

  • 当你需要console.log它(或以其他方式显示为字符串)时,为什么不将其转换为字符串,否则将其用作数字?
  • 我必须将它传递给一个接受数字的外部图表库
  • 所以?将数字传递给库,如果您还需要字符串,请将其转换为字符串并使用它
  • 数字本身不包含任何格式信息。如果不转换为字符串,则无法打印“0.00000006”。而且,正如其他评论者所说,如果您在控制台中将其打印为字符串,则不必更改原始值。

标签: javascript


【解决方案1】:

您可以将其转换为“固定”形状并使其看起来像您想要的那样。例如:

var number = 6e-8; //this is your number
number = number.toFixed(8) //but since you won't always know how many decimal points you have you can use something like
number = number.toFixed(number.toString().split('-')[1]); //where you split your number, see how many decimals it has and pass that number to .toFixed method

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 2020-06-10
    • 2012-06-22
    • 2020-10-28
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 2015-07-03
    相关资源
    最近更新 更多