Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Saving numbers as a string in a csv

I am trying to put a column with a number with leading zeros into a csv file, but it keeps truncating the leading zeros, what can I do to keep them?

Here is the code I am using:

// fopen() here
function clean_zip($string){
    if(preg_match("/^\d{5,}/", $string)){
        $string = str_pad($string, 5, "0", STR_PAD_LEFT);
    }
    return $string;
}

while(($csv = fgetcsv($rhandle)) !== false){
    // other rows here
    $fcsv[9]  = (string)clean_zip($csv[9]);
    fputcsv($whandle, $fcsv);
}

Upvotes: 3

Views: 18673

Answers (3)

Sven
Sven

Reputation: 1540

As already pointed out in the comments, wrapping a number with double quotes (") will result in something like "0123".

The way to go is adding a leading single quote (') as written down in the documentation:

If you decide to enter a number directly as text, enter an apostrophe (') first. For example, for years in column headings, you can enter '1999, '2000 and '2001. The apostrophe is not visible in the cell, it only indicates that the entry is to be recognized as a text. This is useful if, for example, you enter a telephone number or postal code that begins with a zero (0), because a zero (0) at the start of a sequence of digits is removed in normal number formats.

Source: Formatting Numbers as Text

The data is now parsed as a string, which results in it being ignored in a function.

Another way is to format the column as a text column.

Upvotes: 3

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

I just needed to tell Libre Office to display the column as a Text column instead of What ever it thought would be best for the column/cell.

Upvotes: 0

PaulProgrammer
PaulProgrammer

Reputation: 17630

Wrap with double quote characters ("). This is easy enough if you're sure there are only numbers -- if there's a possibility of having quotes in the string you'll have to be more careful.

Upvotes: -1

Related Questions