Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

formatting numbers 2

Status
Not open for further replies.

jimmyJIMMYyaya

Programmer
Sep 30, 2001
13
CA
ok heres the prob

i have the size of a file stored in $filesize. it return the size in kb so i wanted to add the thousands separator to the $filesize ( e.g. 2,345). how do i go about doing this?

any help is greatly appreciated
 
i did this once in a different way (i think a shorter one) but this will do:

$filesize = "199255655";

#when counting for thousands you count by threes from the end
#so we reverse the string, and then reverse it back
$filesize= reverse($filesize);

#using regexps we add commas every three letters
if (length($filesize) >= 4) {
$filesize =~ s/([\d]{3})/$1,/g;
}
#reverse the string back
$filesize= reverse($filesize);

#we check for the first character in the string.
#when processing numbers with length that divides by three
#a comma is added before the string (123456 becomes ,123,456)
$firstchar = substr($filesize,0,1);

#if it's a comma, remove it
if ($firstchar == ",") {
$filesize = substr($filesize,1);
}

#this is it.
print $filesize;

:)
 
A very elegant solution stakadush. One way you could avoid the case of a comma appearing at the front of the string after would be to use a negative zero width look-ahead assertion to make sure the end of string has not been reached:

Code:
    $filesize = s/(\d{3})(?!$)/$1,/g;

Cheers, Neil :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top