PHP - 将数字转换为科学记数法

PHP - Convert number to scientific notation

我有一堆数字总是小于 1。在某些情况下 PHP 将这些数字输出为科学记数法,而在某些情况下只输出数字。

我发现如果数字超过 4 个零小数 (0.0000xyz),则它会显示为科学记数法。我已经能够将科学计数法数字转换为 int,但我想强制使用科学计数法,但一直无法弄清楚如何。

有什么办法可以做到这一点?

您可以使用 %e%E 格式说明符转换为科学记数法 sprintf/printf。

e The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).

E Like the e specifier but uses uppercase letter (e.g. 1.2E+2). – https://www.php.net/manual/en/function.sprintf.php

要获得小数点后一定数量的数字,您可以使用精度说明符,例如%.14e

这是 sprintf 手册中的示例。

Example #6 sprintf(): scientific notation


<?php $number = 362525200;

echo sprintf("%.3e", $number); ?>

The above example will output:

3.625e+8