Re: add_commas()

new topic     » goto parent     » topic index » view thread      » older message » newer message

> Ever notice that there are no commas in the numbers outputed in Euphoria?
>  Qbasic has a PRINT USING that you can use to add commas... Well, here is
>  a Euphoria routine to make your output a little nicer... Feel free to
>  improve on it.
>  So far, you can't set the resolution of the decimals (Like 3,400.00 can't
>  be done easily, it would be 3,400. So feel free to fix that... :)

Here's my 2 cents worth.

Steve Elder

-- code begins here
sequence number2,b,c
atom control, controlb
number2 = ""
b = ""
c = ""
control = 1
controlb = 0

global function add_commas(sequence a)

    -- read input from right to left
    for i = length(a) to 1 by - 1 do
        if a[i] = '.' then
            control = 2
        end if

        -- copy digits right of decimal point with no change
        if control = 1 then
            b = b & a[i]
        -- put in first comma left of decimal point
        elsif control = 2 then
            b = b & a[i]
            controlb = controlb + 1
            if controlb = 4 then
                b = b & ','
                control = 3
                controlb = 0
            end if
        -- put in the rest of the commas
        elsif control = 3 then
            b = b & a[i]
            controlb = controlb + 1
            if controlb = 3 then
                b = b & ','
                control = 3
                controlb = 0
            end if
        end if
    end for

    -- reverse it so the numbers are in the correct order
    for ii = length(b) to 1 by - 1 do
        c = c & b[ii]
    end for
    return c
end function

-- usage example
sequence g
g = add_commas("1123456789.123456")
puts(1,g)

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu