How to change the format of string value and return the string value with defined format
I'm sorry, but I can't point out to the bug in your code if I've never seen the code.
But I show a few tricks to make easier.
First of all, test code in smaller pieces. Don't bother integration your string formatting logic sales order posting if you don't know whether it works at all. You just make debugging much more slower and complicated for you.
Instead, create a runnable class where you'll test your logic. It seems your code doesn't work correctly with values higher than 1000 (maybe because it can't handle strings with more than three characters), therefore that's the obvious scenario to start with. Run the class in debugger and check out where it fails. If it doesn't, you'll at least know that this piece of logic isn't responsible for your problem.
Only when you have this piece of logic working, integrate it with other code and perform integration tests.