I can't fix it, but here is my guess of how it goes wrong.
The algorithm is based on a simple bit of trig. But it has to be fed the correct values to work properly.
I think the NGR is read from the database as six figures. Unfortunately, it is saved in a simple numeric field, so if it has any leading zeros these are ignored. In order to obtain the Eastings, it then reads the first three digits which no longer includes the leading zero, and therefore picks up one of more of the Northings digits. To obtain the Northings it extracts the last three digits, which will always work unless the coordinate starts with four or more zeros.
The correction will therefore require the algorithm to preserve all six digits by treating them as characters and not as numeric. Either that or accommodate the missing zeros by checking the size of the numeric being read. If it is less than 100000, remember to put the appropriate number of zeros back into the string before extracting the Easting.
Now do I get my prize? 🙂