Jump to content

Inserting Commas


N-Bomb(Nerd)

Recommended Posts

Hello,

 

I'm getting a random string of numbers returned from my function, and I'm trying to insert commas every 3 numbers in the string. However, I honestly have no idea where to start with this, because the string that's returned from my function isn't always the same. It's always a whole number, but it my vary in range from 1 to 50,000,000 or greater.

 

For example: Instead of outputting "23236234" it would output "23,236,234".

 

Does anyone know of a method I could use to achieve this?

Link to comment
https://forums.phpfreaks.com/topic/202554-inserting-commas/
Share on other sites

You can use number_format.

 

Well, the problem with using that is that I'm also wanting to apply the same algorithm to a different script of mine (wrote in a different language). Obviously would need tweaked for the other language, but if I can get it to work in php I can get it to work for the other one as well.

 

Kind of need to write the function out so I can see what's happening..  :'(

Link to comment
https://forums.phpfreaks.com/topic/202554-inserting-commas/#findComment-1061858
Share on other sites

Looking through the number_format doc page brings up a couple of alternate implementations.  This one looks ok.

<?php
function FormatNumber($number, $decimals = 0, $thousand_separator = ' ', $decimal_point = '.')
{
  $tmp1 = round((float) $number, $decimals);

  while (($tmp2 = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $tmp1)) != $tmp1)
    $tmp1 = $tmp2;

  return strtr($tmp1, array(' ' => $thousand_separator, '.' => $decimal_point));
}

echo FormatNumber(-913578.1415, 2, '.', ',') . "\n";
?>

Link to comment
https://forums.phpfreaks.com/topic/202554-inserting-commas/#findComment-1061863
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.