Denish
Denish

Reputation: 2810

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.

Upvotes: 3

Views: 4147

Answers (4)

rodrigo-silveira
rodrigo-silveira

Reputation: 13088

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.

Upvotes: 1

Naveen Kumar
Naveen Kumar

Reputation: 4601

$temp=number_format((float)$number, 2, '.', '');

$inter =number_format($temp,2);

$temp1=str_replace(',','.',$inter);
$final=substr_replace($temp1,',',-3,1);

echo"$final";

Hope it helps

Upvotes: 0

Eduardo Iglesias
Eduardo Iglesias

Reputation: 1049

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

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

number_format($input,2,',','.');

That should do it.

Upvotes: 0

Related Questions