Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Number formatting

Is there a filter or method where I can output 12032 as 12,032.

Thanks.

Comments

  • Okay, that was a fun exercise. The trick is to use the eachchar function in reverse to send the number broken down to the addcomma table. The addcomma table is responsible for sending back the character with a comma after it if the count is 3 and setting count back to 0, or sending the character back and incrementing the count. We reverse our reversal at the end and assign all that to a variable. In cases where the length of the number is divisible by 3, we will have a leading comma, so we check if the front of our variable has a comma, remove it if it does or just return the variable.

    Table: Main
    Set: number=1234567891116
    Set: k=0
    Set: MyValue=[[{number} >> reverse >> eachchar AddComma] >> reverse]
    My number started as {number} and was transformed to [when][{MyValue} >> Left]=,[do][{MyValue} >> SubStr 2 0][else]{MyValue}[end]
    EndTable:
    
    Table: AddComma
    Set: k={!{$k}+1}
    [when] {k}=3 [do][@k==0][{$1},][else][{$1}][end]
    EndTable: 
    

  • excellent! I thought of doing a:

    Set: CommaDisplay=[floor($number/1000),[$number-1000]]

    (haven't worked out the bracket syntax yet...)

    but, what I don't like about mine as a permanent fix is that it's only good for number less than 1 million; easy enough to add a floor(number/1000), but then output is like 0,001,123 which is weird. So lots of if's to see how many digits we're dealing with.

    Guess it really doesn't matter that the result of all of these is a string rather than number... the numeric value is still available in original number if further computation is needed.

  • Your last comment got me thinking, what if you got to a place where you have two numbers formatted and want to add them? Well you'd replace the commas with nothing, pass them to an adder table and reformat them. New code below.

    Table: Tester
    Set: TestNum1=[@CNum with {100000d10000}]
    Set: TestNum2=[@CNum with {100000d10000}]
    I'm Adding ${TestNum1} and ${TestNum2} it equals $[@CNum with [@AddFormatted with [{TestNum1} >> replace /,/\/], [{TestNum2} >> replace /,/\/]]]
    EndTable:
    
    Table: CNum
    Set: number={$1}
    Set: count=0
    Set: MyValue=[[{number} >> reverse >> eachchar AddComma] >> reverse]
    [when][{MyValue} >> Left]=,[do][{MyValue} >> SubStr 2 0][else]{MyValue}[end]
    EndTable:
    
    Table: AddComma
    Set: MyChar={$1}
    Set: count={!{$count}+1}
    [when]{count}=3 [do][@count==0][{MyChar},][else][{MyChar}][end]
    EndTable: 
    
    Table: AddFormatted
    {!{$1}+{$2}}
    EndTable:
    

  • Ha! That's nice and it's compact. I think I'll add it to the gemstone generator I made for those 150,000 gp emerald royal orbs.

Leave a Comment