如何防止将非常小的数字转换为科学计数法?

7

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

var x = 0.00000006;

当我运行console.log(x)时,它会显示:
6e-8

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

后来我需要将其绘制在图表上,因此不能将其转换为字符串。如何保持一个小数而不将它转换为字符串或科学计数法?


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

3
你可以将其转换为“固定”形状,并使其看起来符合你的要求。例如:
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

1

这将更加正确,仅在e-符号后的最后一部分不足以始终提供您需要在toFixed中提供的数字。

// containing Scientific Notation to a readable number string
export const convertScientificNotationNumber = (value) => {
    const decimalsPart = value?.toString()?.split('.')?.[1] || '';
    const eDecimals = Number(decimalsPart?.split('e-')?.[1]) || 0;
    const countOfDecimals = decimalsPart.length + eDecimals;
    return Number(value).toFixed(countOfDecimals);
    //0.4210854715202004e-14).toFixed(30)
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接