英文:
javascript how to express many-digit exponentials to 2 decimal places
问题
我有一个JavaScript程序,它在控制台中输出形如'3.173538947635389377E+98'的大数组,经过尝试未能成功将它们缩减为类似'3.17E+98'的形式以便比较。
我将数字转换成字符串,计算小数点和E的位置,然后对字符串进行切割和处理,最终将其变为'317.35E+96'这种形式,其中96是3的倍数。然后,当我使用Number()重新表示为数字时,它又变回了'3.173538947635389377E+98'。
我本可以将它保留为字符串,但后续可能需要重新转换为数字。是否有简单的方法来降低复杂性?当字符串如此之长时,几乎不可能检查和找到相似的数字等。我猜JavaScript的开发人员有他们的原因,但我已经束手无策了。
英文:
I have a javascript program which spits out large arrays of numbers of the form '3.173538947635389377E+98', in the console, and have tried without luck to reduce them to something like '3.17E+98' for ease of comparison.
I Stringified the number, calculated the period and E locations, cut and diced until I had it of the string form '317.35E+96', with 96 as a multiple of 3.
Then when I re-expressed as a number using Number(), it reverted to '3.173538947635389377E+98'.
I could have left it as a string, but then would have to reconvert to Number later on.
Is there a simple way of reducing the complexity? It is nearly impossible to inspect and see similar numbers etc, when the strings are so long. I guess the js people have their reasons, but am at my wits end.
答案1
得分: 2
你可以使用 Intl.NumberFormat
与 engineering
记法:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const display = (n) => new Intl.NumberFormat('en', {
notation: 'engineering',
maximumFractionDigits: 2
}).format(n);
console.log(display(3.173538947635389377E+98));
<!-- end snippet -->
英文:
You can use Intl.NumberFormat
with engineering
notation:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const display = (n) => new Intl.NumberFormat('en', {
notation: 'engineering',
maximumFractionDigits: 2
}).format(n);
console.log(display(3.173538947635389377E+98));
<!-- end snippet -->
答案2
得分: 1
你可以使用 toFixed()
方法将多位数的指数表示为小数点后两位。
例如,
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var num = 3.14159265358979323846264338327950;
var result = num.toFixed(2);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
// 结果将是 3.14
英文:
You can use the toFixed()
method to express many-digit exponentials to two decimal places.
For example,
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var num = 3.14159265358979323846264338327950;
var result = num.toFixed(2);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
<!-- end snippet -->
// result will be 3.14
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论