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
4
  • Does this answer your question? How to prefix a positive number with plus sign in PHP
    – Kerkouch
    Feb 28, 2020 at 7:33
  • Probably what are you looking for is sprintf("%+.1f", $num1)
    – Kerkouch
    Feb 28, 2020 at 7:34
  • Just use the NumberFormatter class for formatting numbers. I 've posted an example how to use it as an answer.
    – Marcel
    Feb 28, 2020 at 7:38
  • jogin shar "If an answer solved your problem, consider accepting the answer. Here's 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!" Mar 12, 2020 at 6:58

3 Answers 3

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.

0

In python, you could do it like this:

def returnWithSign(str):
      n = float(str)
      if n>0:
         return '+{}'.format(n)
      return n
1
  • why python? is op asked answer in python? I am not able to see any tag suggested python as well Feb 28, 2020 at 7:31
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

1
  • 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. Mar 3, 2020 at 6:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.