PHP 编号:将 1.4E-N (N >40) 转换为十进制,并删除无用的零位



我从第三方服务中获得的值很小,我需要将其转换为已删除无用数字的数字。

<?php 
    $decimal = 50 
    //If value is 1.4E-45
    number_format($value, $decimal); 
    //output: 0.00000000000000000000000000000000000000000000140000 
    number_format($value, $decimal) +0 ;
    //output: 1.4E-45 
?>

`

样本输入::

  • 1

    输出1

  • 1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

    输出:1

  • 1.4e-45

    输出:0.00000000000000000000000000000000000000000000000014

您可以在代码中看到,已经尝试添加0和number_format方法。

可以有两种方法

  1. 发现需要动态使用$小数值
  2. 始终将最大可能的$十进制值传递给无用的0。我们可以假设上限为50美元。

请建议使用PHP功能中的任何方法

我建议这种方法:

<?php

function getRidOfExtraZeros($str)
{
    // Don't want to rtrim whole numbers
    if(strpos($str,'.') === false ){ return $str; }
    // Don't want to rtrim scientific notation
    if(stripos($str,'e') !== false ){ return $str; }
    // We're good to go
    return rtrim(rtrim($str, '0'),'.');
}
$value = '0.00000000000000000000000000000000000000000000140000';
echo getRidOfExtraZeros($value),"n"; // 0.0000000000000000000000000000000000000000000014
echo getRidOfExtraZeros('30'),"n"; // 30
echo getRidOfExtraZeros('30.79e10'),"n"; // 30.79e10
echo getRidOfExtraZeros('0.0'),"n"; // 0
echo getRidOfExtraZeros('0.'),"n"; // 0

如果您不介意在边缘案例中精确丢失并看到一些科学符号,则可以将绳子置于浮动。精心使用的RTRIM可能是最好的方法。

您将小数设置为50,这就是为什么它输出最后一个零。
如果您计算出什么$小数,则应该为您提供所需的东西。

$value = 0.0000000000000000000000000000000000000000000014;
// Find what the number is 
$end = str_replace(".", "", explode("E-", $value)[0]); // 14
// Find consecutive zeros to $end
Preg_match("/.d+" . $end ."/", number_format($value, 100), $match);
$decimal = strlen($match[0])-1; // make that number the end -1 due to the dot
Echo number_format($value, $decimal);

https://3v4l.org/fe1xd

它不是很漂亮,但为此有用。

编辑:我有numberFormat($ values, 100 (,因为我需要确保将完整的数字作为浮点数。
然后,我使用preg_match查找模式[0]以及您在此float号码上的号码。

编辑2。这将向您展示为什么固定的小数不是一个好的解决方案。
浮数不精确。
https://3v4l.org/ai0ke

最新更新