1

I am to display New Zealand and Australian bank accounts in reports, formatted according to a custom format supplied by the user. For example, NZ bank accounts can be 00-0000-0000000-000 with the last digit (bank account suffix) being optional. There are two parts of the format:

  • Placement of dashes
  • 2 digit prefix

Sample formatted bank accounts can be 01-1234-1234567-55 and 01-1234-1234567-002. The bank accounts are stored in the database without any formatting. When I tried String.Format("{0:00-0000-0000000-00#}",121234123456712) it does not return the expected 12-1234-1234567-12 but 01-2123-4123456-712.

Understandably I could always test the length of the bank account and do a switch statement, but the format is user defined.

The following ensures the dashes are placed correctly and the suffix is correct:

// ensure there is a format to use and a bank account is present
if (bankaccountformat != "" && bankaccountformat.Contains('-') && bankaccount != "")
{
  int i = 0;
  foreach (char dash in bankaccountformat)
  {
    // add dash in bank account, if bank account is long enough
    if (dash == '-' && bankaccount.Length > i)
    {
      bankaccount = bankaccount.Insert(i, "-");
    }
    i++;
  }
}

The issue is not if the account is valid or not, it is the formatting. Please let me know of a better way to format the account.

1 Answers1

0

You do not mention which programming language you use. Anyhow, it seems you use an array. That can be tricky.

In BASH I would use string manipulation, like in this script (fmat):

#!/bin/bash

#only numbers allowed
[[ ! "$1" =~ ^[0-9]+$ ]] && echo "Error: enter numbers only" && exit

s=$1
l=${#s}
r=l-13

#minimal number of digits is 13, maximum 16
[[ r -lt 0 || r -gt 3 ]] && echo "Error: enter 13-16 digits" && exit

#first 13 digits
a=${s:0:2}"-"${s:2:4}"-"${s:6:7}

#when 14-16 digits
a=$a"-"${s:13:r}

echo $a

fmat 011234123456755 gives 01-1234-1234567-55

fmat 0112341234567002 gives 01-1234-1234567-002

fmat 0112341234567 gives 01-1234-1234567

If you use something else than BASH, then at least this gives some hints.

linuph
  • 83
  • 3
  • 6