Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Formatting Numbers For Output
Index -> Programming, Turing -> Turing Submissions
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
ClayWall




PostPosted: Fri Jan 02, 2009 10:54 pm   Post subject: Formatting Numbers For Output

I wanted to output some numbers with commas separating every third digit as is the way numbers are commonly formatted. I use one parameter to collect the number to be formatted. Then in reverse I put a comma after every third number. After that I reversed the whole number to read correctly. This creates a way of outputting a number to be visually appealing but does not change a variables value, so the number can be continually formatted. This can even be used with Font.Draw.

code:

function FormNum (num : int) : string
    var reverse : string := ""
    var complete : string := ""
    var digits : string := intstr (num)
    var counter : int := 0
    for decreasing x : length (digits) .. 1
        reverse += digits (x)
        counter += 1
        if counter = 3 and x not= 1 then
            reverse += ","
            counter := 0
        end if
    end for
    for decreasing x : length (reverse) .. 1
        complete += reverse (x)
    end for
    result complete
end FormNum

put FormNum (1234567890)
var num : int := 1000
var font : int := Font.New ("courier new:12")
Font.Draw (FormNum (num), 50, 50, font, black)


This is nothing special, but I thought it might just be what some people were looking for in their programs.

EDIT: Had to add a check to make sure a comma was not added to the beginning of the number being formatted.
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Turing -> Turing Submissions
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: