gpt4 book ai didi

php - 将 float 转换为纯字符串表示形式

转载 作者:行者123 更新时间:2023-12-02 23:48:49 25 4
gpt4 key购买 nike

所以,

问题

我的问题是关于琐碎的事情:如何将数字字符串转换为其简单的(“ native ”)表示形式。这意味着:如果数字字符串已经在普通 View 中,则保持原样,但如果它是科学记数法,则将其转换。示例:

"3"          -->  "3""1.5"        -->  "1.5""-15.482E-2" -->  "-0.15482"

Numeric string supposed to be valid, and if it's not - then it's not a case for conversion (we're free to return null or empty string, for example).

Use-case

That is needed for bcmath because it can't work with scientific floats. Thus, they need to be converted to plain strings (asked here). So important consequence from this use-case is that numeric string can be something like 1E-300 or 1E+500. Since we're working with bcmath - it's intention is to handle such things.

My approach

For now, I've implemented that with , like:

function parseFloat($string)
{
$string = (string)$string;
if(preg_match('/^[+-]?(\d+|\d+\.\d*)[Ee]([+-]?)(\d+)$/', $string, $matches))
{
$precision = false!==($dot=strpos($matches[1], '.'))
?strlen($matches[1])-$dot-1
:0;
$precision = $matches[2]=='-'
?$precision + (int)$matches[3]
:$precision - (int)$matches[3];
return number_format($string, $precision<0?0:$precision, '', '');
}
if(preg_match('/^[+-]?(\d+|\d+\.\d+)$/', $string))
{
return $string;
}
}

问题

我觉得应该有更简单、更明智的方法来做到这一点。如何在 PHP 中以更简单的方式实现这一点?可能有些棘手sprintf()格式?

重要说明:我不想处理精度问题。我想要黑匣子。在那里传递一些数字 - 将字符串作为输出。就这样。不想处理其他事情。事实上,我所有的正则表达式都是关于计算长度和精度的 - 所以,当然,如果显式传递它们(例如作为参数) - 我们就可以摆脱正则表达式。但是 - 不,这不是我想要的。

最佳答案

由于 sprintf()"%.f" 在处理诸如 "1e-8" 之类的表达式时存在问题,某些文本处理可能会出现问题需要:

function convertFloat($floatAsString)
{
$norm = strval(floatval($floatAsString));

if (($e = strrchr($norm, 'E')) === false) {
return $norm;
}

return number_format($norm, -intval(substr($e, 1)));
}

测试使用:

3          3
1.5 1.5
-15.482e-2 -0.15482
1e-8 0.00000001
1e+3 1000
-4.66E-2 -0.0466
3e-3 0.003

关于php - 将 float 转换为纯字符串表示形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21902817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com