Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need help in PHP number format

Hello everyone i am trying to format the input number range with php number_format

INPUT Probability

  1. 1234
  2. 12345
  3. 123456789
  4. 123456789,50
  5. 123.45,00
  6. 123.456.78,50

OUTPUT should be

dot should be in multiplier of 3 digit and last two (if available in input range) digits should be come with comma separater

  1. 1.234,00
  2. 12.345,00
  3. 123.456.789,00
  4. 123.456.789,50
  5. 12.345,00
  6. 12.345.678,50

out put should be as per dutch format and dot should be in multiplier of 3 digit and last two digits should be come with comma separater

like, here is link you can put any input value from above list in textbox you can get output like shown below

the code which i am using

echo numberFormat('12345');

function numberFormat($num)
{
     return preg_replace("/(?<=\d)(?=(\d{3})+(?!\d))/",".",$num);
}

but it will not work with (4),(5),(6) from my input probability to match with outputs.

like image 685
Denish Avatar asked Oct 27 '25 12:10

Denish


2 Answers

Well I think is like this:

$number = 1234.56
echo number_format($number, 2, ',', '.');

About the input yo could check and all the "." remove it and the "," replace with "."

$number = "123.456,78";
$temp = str_replace(".", "", $number);
$temp2 = str_replace(",", ".", $temp);
echo number_format($temp2, 2, ',', '.');

I hope it helps

like image 197
Eduardo Iglesias Avatar answered Oct 30 '25 02:10

Eduardo Iglesias


This is pretty similar to @Emesto solution, but forced into a number:

$num = '123.456.789,50';
$n = str_replace('.', '', $num);
$n = str_replace(',', '.', $n);

# $n is no longer a string
$n = $n + 0;

# so it should work fine in number_format
echo number_format($n,2,',','.');

PS: I just tested this code to be sure that it works.

like image 21
rodrigo-silveira Avatar answered Oct 30 '25 01:10

rodrigo-silveira