Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2

Thread: number formats

  1. #1
    New to the CF scene
    Join Date
    Sep 2002
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    number formats

    hi,

    i have a txt file with numbers in it. i want to change all the one digit number to two digit format. e.g "5" -> "05" how do i do this?

    thx

  • #2
    Regular Coder
    Join Date
    Jul 2002
    Location
    London, UK
    Posts
    126
    Thanks
    0
    Thanked 0 Times in 0 Posts
    If you want to do formatting on a number/string the functions to use are printf and sprintf, the difference being that sprintf returns a formatted string whilst printf prints a formatted string.

    Here's some example code to help with your problem:
    Code:
    #!/usr/bin/perl
    
    open (DATA, "data.tst") || die "Couldn't open data.tst for reading: $!";
    while (<DATA>) {
    	$data .= $_;
    }
    close DATA;
    
    $data =~ s/\b(\d+)\b/sprintf("%.02d", $1)/eg;
    
    open (DATA, ">data.tst") || die "Couldn't open data.tst for writing: $!";
    print DATA $data;
    close DATA;
    
    print "Done!\n";
    Where data.tst is the file with your numbers in.
    The key code here is the regular expression, it works like this:
    -match a word boundary
    -match one or more digits (save for later use)
    -match another word boundary
    and replace this with a zero-padded form of the number of length 2 digits minimum, so 1 would become 01, 5 would become 05 and anything of 2 digits or more would stay as it is.

    This will only match numbers that are on their own, i.e. this:
    lalala2foobar
    would stay the same.

    If you wanted to change its behaviour so that the above would change to this:
    lalala02foobar
    You would need to change the regular expression to:
    Code:
    $data =~ s/(\d+)/sprintf("%.02d", $1)/eg;
    Hope that helps.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •