首页 > 解决方案 > 在 JavaScript 中将数字 (e+) 的指数表示法转换为 10^

问题描述

我有一个脚本,我可以在其中将 gigs 转换为 megs 到千字节到字节到位。

之后,它使用该.toExponential函数将其转换为科学计数法。

但我希望它变成一个指数,而不是+e#我想要它是^#,任何方式我都可以改变它来打印,如果不是,无论如何我可以改变字符串来+e改变^

代码:

console.log('calculator');
const gigabytes = 192;
console.log(`gigabytes equals ${gigabytes}`);
var megabytes = gigabytes * 1000;
console.log(`megabytes = ${megabytes}`);
var kilabytes = megabytes * 1000;
console.log (`kilabytes = ${kilabytes}`);
bytes = kilabytes * 1000;
console.log(`bytes = ${bytes}`);
bites = bytes * 8;
console.log(`bites are equal to ${bites}`);
console.log (bites.toExponential());

标签: javascriptmath

解决方案


您可以使用.replace

const bytes = '1.536e+12'
console.log(convert(bytes))

const inputs = [
  '1.536e+12',
  '1.536e-12',
  '123',
  '-123',
  '123.456',
  '-123.456',
  '1e+1',
  '1e-1',
  '0e+0',
  '1e+0',
  '-1e+0'
]

function convert(value) {
  return value.replace(/e\+?/, ' x 10^')
}

inputs.forEach(i => console.log(convert(i)))


推荐阅读