php如何将数字转换成科学计数法

如何将0.00001转换成1.00E-05 ?

阅读 4.6k
4 个回答

php 自带函数
参考官方文档 sprintf

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).

可以直接写函数进行实现

之前写了一个,不过都是正数的,负数的话先把前面的负号去掉在用

function science($num){
    if($num > 1){
        $temp = $num;
        $pow = strlen($temp)-1;
    }else{
        $temp = 1/$num;
        $pow = -(strlen($temp)-1);
    }

    $base = $temp/pow(10, abs($pow));
    return  $base.'E'.$pow;
}

Fractal大佬的方法更好,我之前没发现,学习到了。

搜索一下就知道了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题