0

I am trying to get number value with plus and minus

<?php
$num1= '-12.20000';
$num2= '+18.20000';

echo rtrim(str_replace('.00', '', number_format($num1, 2));
echo rtrim(str_replace('.00', '', number_format($num2, 2));

?>

Need output like

-12.2
+18.2
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
jogin shar
  • 31
  • 7
  • Does this answer your question? [How to prefix a positive number with plus sign in PHP](https://stackoverflow.com/questions/2682397/how-to-prefix-a-positive-number-with-plus-sign-in-php) – Kerkouch Feb 28 '20 at 07:33
  • Probably what are you looking for is `sprintf("%+.1f", $num1)` – Kerkouch Feb 28 '20 at 07:34
  • Just use the `NumberFormatter` class for formatting numbers. I 've posted an example how to use it as an answer. – Marcel Feb 28 '20 at 07:38
  • jogin shar "If an answer solved your problem, consider accepting the answer. Here's [How does accepting an answer work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). Then return here and do the same with the tick/check-mark till it turns green. This informs the community, a solution was found. Otherwise, others may think the question is still open and may want to post (more) answers. You'll earn points and others will be encouraged to help you. Welcome to Stack!" – Alive to die - Anant Mar 12 '20 at 06:58

3 Answers3

1

I can't see exactly what you need. There are not enough examples and your description of the task is not sufficient.

The number is formatted with a sign and 2 decimal places. If the last digit is a 0, it is removed with preg_replace().

$data = ['-12.20000','+18.20000', 234.0, 2.1234];

foreach($data as $value){
  $formatVal = sprintf("%+0.2f",$value);
  $formatVal = preg_replace('~(\.\d)0$~','$1',$formatVal);

  echo $value.' -> '.$formatVal."<br>\n";
}

Output:

-12.20000 -> -12.2
+18.20000 -> +18.2
234 -> +234.0
2.1234 -> +2.12

If the result is only ever required with one decimal place, you can use

$formatVal = sprintf("%+0.1f",$value);

without the preg_replace.

jspit
  • 7,276
  • 1
  • 9
  • 17
0

In python, you could do it like this:

def returnWithSign(str):
      n = float(str)
      if n>0:
         return '+{}'.format(n)
      return n
RAHUL MAURYA
  • 128
  • 8
0

Instead of using difficult functions in PHP just use the native stuff PHP brings with it. One fantastic thing of that stuff is the NumberFormatter class.

$formatter = new NumberFormatter( 'en_GB', NumberFormatter::DECIMAL );
$formatter->setTextAttribute(NumberFormatter::POSITIVE_PREFIX, '+');  
$num1= '-12.20000';
$num2= '+18.20000';

echo $formatter->format($num1) . PHP_EOL;
echo $formatter->format($num2) . PHP_EOL;

Exactly does what you want.

Output: https://3v4l.org/UQX3Y

Marcel
  • 4,854
  • 1
  • 14
  • 24
  • please mention that function is available in higher PHP version `((PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0))`. Though very good and correct solution among all. – Alive to die - Anant Mar 03 '20 at 06:16