如何在 PHP 中为正数添加加号前缀

发布于 2024-08-30 05:03:02 字数 324 浏览 5 评论 0原文

我需要设计一个函数以不变地返回负数,但如果数字已经不存在,则应在数字的开头添加一个 + 符号。

示例:

Input     Output
----------------
+1         +1
1          +1
-1         -1

它将仅获得数字输入。

function formatNum($num)
{
# something here..perhaps a regex?
}

该函数将在 echo/print 中调用多次,因此越快越好。

I need to design a function to return negative numbers unchanged but should add a + sign at the start of the number if its already no present.

Example:

Input     Output
----------------
+1         +1
1          +1
-1         -1

It will get only numeric input.

function formatNum($num)
{
# something here..perhaps a regex?
}

This function is going to be called several times in echo/print so the quicker the better.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

禾厶谷欠 2024-09-06 05:03:02

您可以将正则表达式用作:

function formatNum($num){
    return preg_replace('/^(\d+)$/',"+$1",$num);
}

但我建议不要使用正则表达式来处理如此琐碎的事情。最好在这里使用 sprintf

function formatNum($num){
    return sprintf("%+d",$num);
}

来自 sprintf 的 PHP 手册

强制在数字上使用符号(- 或 +)的可选符号说明符。默认情况下,如果数字为负数,则仅使用 - 符号。 此说明符强制正数附加 + 号,并在 PHP 4.3.0 中添加。

You can use regex as:

function formatNum($num){
    return preg_replace('/^(\d+)$/',"+$1",$num);
}

But I would suggest not using regex for such a trivial thing. Its better to make use of sprintf here as:

function formatNum($num){
    return sprintf("%+d",$num);
}

From PHP Manual for sprintf:

An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.

江湖正好 2024-09-06 05:03:02
function formatNum($num) {
   return ((float) $num>0)?'+'.$num:$num;
}
function formatNum($num) {
   return ((float) $num>0)?'+'.$num:$num;
}
泪眸﹌ 2024-09-06 05:03:02
function formatNum($num) {
  $num = (int) $num; // or (float) if you'd rather
  return (($num >= 0) ? '+' : '') . $num; // implicit cast back to string
}
function formatNum($num) {
  $num = (int) $num; // or (float) if you'd rather
  return (($num >= 0) ? '+' : '') . $num; // implicit cast back to string
}
山人契 2024-09-06 05:03:02

简单的解决方案是在 printf() 函数中使用格式说明符。

例如,

$num1=2;
$num2=-2;
printf("%+d",$num1);
echo '<br>';
printf("%+d",$num2);

给出输出

+2
-2

在您的情况下

 function formatNum($num){
    return printf("%+d",$num);
 }

The simple solution is to make use of format specifier in printf() function.

For example,

$num1=2;
$num2=-2;
printf("%+d",$num1);
echo '<br>';
printf("%+d",$num2);

gives the output

+2
-2

In your case

 function formatNum($num){
    return printf("%+d",$num);
 }
晨与橙与城 2024-09-06 05:03:02

试试这个:

$fmt = new NumberFormatter('es_ES', NumberFormatter::DECIMAL);
$fmt->setTextAttribute(NumberFormatter::POSITIVE_PREFIX, '+');
$result = $fmt->format(10000);

结果将是:+10.000

完全有效 NumberFormatter::POSITIVE_SUFFIX,您将收到 10.000+

Try this:

$fmt = new NumberFormatter('es_ES', NumberFormatter::DECIMAL);
$fmt->setTextAttribute(NumberFormatter::POSITIVE_PREFIX, '+');
$result = $fmt->format(10000);

Result will be: +10.000

Exactly works NumberFormatter::POSITIVE_SUFFIX, you will receive 10.000+

清风疏影 2024-09-06 05:03:02

好吧,这是相当旧的,可能没用,但我认为仍然有一些空间可以稍微补充。如果您已“准备好”数字:

if($num>=0) $num='+'.(0+$num);

或者,如果您确定它是一个数字:

if($num>=0) $num='+'.$num;
  • 这对负数没有任何作用,如果是正数,则仅更改为字符串。

  • 如果不是,则添加 0 会转换为 Number,并且不会更改数字类型,例如转换为 (float) 或 (int)。如果你确定它是一个数字,则没有用,请使用第二个版本。

  • 这可能是最快的方法

  • 缺点是,您将得到一半结果为字符串,一半结果为数字(sprintf 将使它们全部为字符串)

Ok, this is rather old and probably useless, but I think there is still some space for a slight addition. If you have the number "ready":

if($num>=0) $num='+'.(0+$num);

Or, if you are sure it's a number:

if($num>=0) $num='+'.$num;
  • This does nothing on negative numbers and just changes to string if positive.

  • Adding 0 converts to Number if it is not, and does not change the numeric type, like casting to (float) or (int). It is useless if you are sure it's a number, use the second version.

  • This is probably the quickest way

  • As a downside, you will have half results as strings and half as numbers (sprintf will make them all strings)

街角迷惘 2024-09-06 05:03:02

@unicornaddict 提供的 sprintf 解决方案非常好,而且可能是最优雅的方法。只是想无论如何我都会提供一个替代方案。不确定他们的速度如何。

// Non float safe version
function formatNum($num) {
    return (abs($num) == $num ? '+' : '') . intval($num);
}

// Float safe version
function formatNum($num) {
    return 
        (abs($num) == $num ? '+' : '') 
        . (intval($num) == $num ? intval($num) : floatval($num));
}

// Float safe version, alternative
function formatNum($num) {
    return 
        (abs($num) == $num ? '+' : '') 
        // Add '1' to $num to implicitly cast it to a number
        . (is_float($num + 1) ? floatval($num) : intval($num));
} 

The sprintf solution provided by @unicornaddict is very nice and probably the most elegant way to go. Just thought I'd provide an alternative anyway. Not sure how they measure up in speed.

// Non float safe version
function formatNum($num) {
    return (abs($num) == $num ? '+' : '') . intval($num);
}

// Float safe version
function formatNum($num) {
    return 
        (abs($num) == $num ? '+' : '') 
        . (intval($num) == $num ? intval($num) : floatval($num));
}

// Float safe version, alternative
function formatNum($num) {
    return 
        (abs($num) == $num ? '+' : '') 
        // Add '1' to $num to implicitly cast it to a number
        . (is_float($num + 1) ? floatval($num) : intval($num));
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文