Computer Science Canada

Procedure to turn integers into formatted strings

Author:  Aange10 [ Sun Apr 08, 2012 9:00 pm ]
Post subject:  Procedure to turn integers into formatted strings

I jotted this program down a bit ago and figured I'd share it with you guys. I wanted this in the past and I'm happy I actually made this, anyways, this will just take in a number and output a string with commas inserted


Turing:

fcn aC (number : int) : string
    % AC stands for Add commas. This function takes a number and outputs a string
    % with commas in the appropiate place
    var outputString : string := intstr (number)
    if length (outputString) >= 4 then
        % if there are 4 or more characters find how many commas are needed
        var neededCommas : int := length (outputString) div 3
        var addIn : int := -1 % This will add in the extra spacing the comma takes
        for i : 1 .. neededCommas
            addIn += 1
            % Make sure we arent on the first character
            outputString := outputString (1 .. length (outputString) - ((i * 3) + addIn)) +
                "," +
                outputString (length (outputString) - ((i * 3) + addIn) + 1 .. length (outputString))
        end for
    else
        result outputString
    end if
    if outputString (1) = "," then
        outputString := outputString (2 .. length (outputString))
    end if
    result outputString
end aC




For example:
Turing:

    aC (2000) % -> "2,000"
    aC (21234) % -> "21,234"
    aC (001) % -> "1"
    aC (001111) % -> "1,111"
    aC (11) % -> "11"
    aC(213123123) -> "213,123,123"


: