Friday, January 22, 2010

Maxim 1: Zero pad numbers in strings

If you store a number in a file name or any string really, then zero pad it. Why? Because some system will want to sort it alphabetically and well if you don't zero pad it then your numbers will not be in order.

4 comments:

Peter Becker said...

That's a bit COBOL, isn't it? Humans would probably find leading zeros weird and harder to read. You also commit yourself to a fixed number of digits.

Most file browsers nowadays manage to sort numerically. I know a lot of tools don't -- and for those it might be good to zero pad numbers. But then -- you can always fix that with a bit of scripting if necessary.

Richard Cole said...

For presentation to a user you can remove zero as required, but for API's that provide pagination via alphabetical sorting, you need the zeros in there. If you can store the index as a number rather than a string, well that is better, but then you're not using a string any more, so the maxim doesn't apply.

Daumier said...

How many zeros?

Richard Cole said...

Enough zeros, depends if your numbers are 32 or 64 bit.