Jump to content

Format number to add comma


jezzzzy
 Share

Recommended Posts

I have looked in the help file and searched the forum but have been unable to find a solution to what seems like a simple formatting issue. I need a variable that is a number to be displayed with the comma (,) character seperating thousands. IE. My variable now returns as 16235 and I would like it to display 16,235.

Link to comment
Share on other sites

I have looked in the help file and searched the forum but have been unable to find a solution to what seems like a simple formatting issue. I need a variable that is a number to be displayed with the comma (,) character seperating thousands. IE. My variable now returns as 16235 and I would like it to display 16,235.

StringFormat is your friend. You need to think about. At least with all those formats you can do what you want.

Tell me If I am right ;)

Link to comment
Share on other sites

also you might want to check out the following thread: http://www.autoitscript.com/forum/index.ph...wtopic=11732&hl=

Many lines. My code experience is in ASP/VB and I was hoping there was a "FormatNumber()" or something similar. I will review both the AddComma() function in the referenced thread and "StringFormat" and figure out which is most efficient - unless there is a subsequent reply with a better idea. I don't want a lot of bloat.

Thank you both for the help.

StringFormat is your friend. You need to think about. At least with all those formats you can do what you want.

Tell me If I am right ;)

It may be due to my lack of knowledge, but I cannot see a way that "stringformat" will accomplish what I am looking for. Lots of options for number formatting, but I don't see any that will add my comma.

Link to comment
Share on other sites

I have looked in the help file and searched the forum but have been unable to find a solution to what seems like a simple formatting issue. I need a variable that is a number to be displayed with the comma (,) character seperating thousands. IE. My variable now returns as 16235 and I would like it to display 16,235.

i am writing a Funktion which may help you, but it is not finished yet

Global Const $sGrouping = StringLeft(RegRead("HKEY_CURRENT_USER\Control Panel\International", "sGrouping"),1)

Global Const $sMonGrouping = StringLeft(RegRead("HKEY_CURRENT_USER\Control Panel\International", "sMonGrouping"),1)

Global Const $iCurrDigits = RegRead("HKEY_CURRENT_USER\Control Panel\International", "iCurrDigits")

Global Const $sMonThousandSep = RegRead("HKEY_CURRENT_USER\Control Panel\International", "sMonThousandSep")

Global Const $sMonDecimalSep = RegRead("HKEY_CURRENT_USER\Control Panel\International", "sMonDecimalSep")

Global Const $sCurrency = RegRead("HKEY_CURRENT_USER\Control Panel\International", "sCurrency")

Func _FormatNumber($iAmount, $iDecimals = 0)

if $iAmount <> "" And IsString($iAmount) Then

Local $len = StringLen($iAmount)

if $iDecimals <> 0 Then

$dec = $sMonDecimalSep & StringRight($iAmount,$iDecimals)

Else

$dec = ""

EndIf

ConsoleWrite($len & @cr)

$iAmount = StringTrimRight($iAmount,$iDecimals)

$len = $len - $iDecimals

Local $sAmountCurrency = $dec & " " & $sCurrency

Dim $iGroups_temp = $len / $sMonGrouping

ConsoleWrite($len & @cr)

ConsoleWrite($sMonGrouping & @cr)

ConsoleWrite($iGroups_temp & @cr)

if (isint($iGroups_temp)) Then

$iGroups = $iGroups_temp

Else

$iGroups = int($iGroups_temp) +1

Endif

Dim $aThousand[$iGroups]

If $iGroups > 1 Then

ConsoleWrite(UBound($aThousand)-1 &@CR)

for $i = 0 to UBound($aThousand)-1

$aThousand[$i] = StringRight($iAmount,$sMonGrouping)

$iAmount = StringTrimRight($iAmount,$sMonGrouping)

Next

for $i = 0 to UBound($aThousand)-1

if $i = UBound($aThousand)-1 then

$sAmountCurrency = $aThousand[$i] & $sAmountCurrency

Else

$sAmountCurrency = $sMonThousandSep & $aThousand[$i] & $sAmountCurrency

EndIf

Next

ElseIf $iGroups <=1 Then

$sAmountCurrency = $iAmount & $sAmountCurrency

EndIf

return $sAmountCurrency

EndIf

EndFunc

ConsoleWrite(_FormatNumber("4421312351")&@cr)

Link to comment
Share on other sites

I will review both the AddComma() function

Hi jezzzzy-

I checked out the AddComma() function and it works great. Keep in mind that the code at the top of the code listing is a built in test of the function itself. You don't need all that code, just the part from "func" to "endfunc". Put that code in a file called AddComma.au3 and save it in your "include" folder. Then you can call it from your script by having #include <AddComma.au3> at the top and using the function _addcomma("12345567") or _addcomma($myvariable).

The reason there is as much code as there is, is because he checks for decimal values, tests to see if the string is less than 3 digits, etc... It really is a good solution.

...by the way, it's pronounced: "JIF"... Bob Berry --- inventor of the GIF format
Link to comment
Share on other sites

Hi jezzzzy-

I checked out the AddComma() function and it works great. Keep in mind that the code at the top of the code listing is a built in test of the function itself. You don't need all that code, just the part from "func" to "endfunc". Put that code in a file called AddComma.au3 and save it in your "include" folder. Then you can call it from your script by having #include <AddComma.au3> at the top and using the function _addcomma("12345567") or _addcomma($myvariable).

The reason there is as much code as there is, is because he checks for decimal values, tests to see if the string is less than 3 digits, etc... It really is a good solution.

It does work well. I will use it. Thank you all.
Link to comment
Share on other sites

Jezzzy,

Many lines. My code experience is in ASP/VB and I was hoping there was a "FormatNumber()" or something similar. I will review both the AddComma() function in the referenced thread and "StringFormat" and figure out which is most efficient - unless there is a subsequent reply with a better idea. I don't want a lot of bloat.

Thank you both for the help.

It may be due to my lack of knowledge, but I cannot see a way that "stringformat" will accomplish what I am looking for. Lots of options for number formatting, but I don't see any that will add my comma.

I am busy with one - does'nt use the registry.

Beware ;):P , code is still dirty - just trying to get some results.

;===============================================================================
;
; Description:    Converts a currency string from 
;                            1000000.00 to 1,000,000.00
;                            $1000000.00 to $1,000,000.00
;                            1000000.00$ to 1,000,000.00$
;                      
; Parameter(s):  $sCurrency     -   String containing the Currency Amount
;                  $cDecimalChar    -   Decimal point character (default='.')
;                  $nWidth          -   Number of characters between delimiters (default=3)
;                  $cChar           -   Delimiter Character (default=',')
;                  $sHasCSymbol -   Does sCurrency contains a currency Symbol (default=0)
;                                              0 - No Symbol
;                                              1 - Yes (prefix)
;                                              2 - No (suffix)
;                  $nCSymbolSize    -   Size of Currency Symbol (default=0)
;                                              0 - No Symbol
;                                              n - Sysmbol size (in chars)
; Requirement(s):   None
; Return Value(s):  On Success - Returns the formatted Currency String
;                  On Failure - 0  and sets @ERROR = 1
; Author(s):        Douglas van Vliet
; Note(s):        None
;
;===============================================================================
Func _StringCurrencyFormat($sCurrency, $cDecimalChar='.', $nWidth=3, $cChar=',', $sHasCSymbol=0, $nCSymbolSize=0)
    Local $sNewCurrency, $aCurrency[5], $sCurrValue, $sSymbol, $nLength, $nNoDel, $aStripCommas

;MsgBox(4096,"$sCurrency",$sCurrency)

    $aCurrency = 0
    $aStripCommas = 0
    
;Strip all $cChar from SUmAssured/Premium - previous calculation
    $aStripCommas = StringSplit($sCurrency, $cChar)
    $sStrippedCurrency = ""
    For $idx = 1 to $aStripCommas[0] 
        $sStrippedCurrency &= $aStripCommas[$idx]
    Next
    
; Verify If $sCurrency is valid - First Char is not a $cDecimalChar
    If (StringLeft($sCurrency,1) = $cDecimalChar) Then
        SetError(1)
        Return $sCurrency
    EndIf
    
;Split the Value into Dollars and Cents
    $aCurrency = StringSplit($sStrippedCurrency, $cDecimalChar)
;MsgBox(4096,"$sCurrency", "$sStrippedCurrency" & $sStrippedCurrency & " - " & $aCurrency[0] & " - $aCurrency[1]" & $aCurrency[1])
;MsgBox(4096,"Len of $aCurrency[1]",StringLen($aCurrency[1])&"  -  "&$aCurrency[1])
    If StringLen(StringStripWS($aCurrency[1],3))<=$nWidth Then
        SetError(1)
        Return $sStrippedCurrency
    EndIf
; Valid string - Check for Currency Symbol
    If $sHasCSymbol = 0 Then ; No Symbol
        If $nCSymbolSize > 0 Then ; Parameter error
            SetError(1)
            Return $sStrippedCurrency
        EndIf
        $sSymbol = ""; no symbol
        $sDelValue = $aCurrency[1]
    Else
        If $sHasCSymbol = 1 Then
            $sSymbol = StringLeft($aCurrency[1],$nCSymbolSize); prefix
            $sDelValue = StringMid($aCurrency[1], $nCSymbolSize+1)
        Else ;suffix
            If $aCurrency[0]>1 Then; is a decimal point
                $sSymbol = StringRight($aCurrency[2],$nCSymbolSize); suffix
                $sDelValue = $aCurrency[1]
            EndIf
        EndIf
    EndIf
; create the new string - include delimters
    $nLength = StringLen($aCurrency[1])
    $nNoDel = _Floor( $nLength / $nWidth)
    $nPreDel = $nLength - ($nNoDel * $nWidth)
    $sDelStr = ""
    If $nPreDel > 0 Then
        $sDelStr = StringLeft($sDelValue,$nPreDel); First portion of String + Delimiter char
    EndIf
    $nCnt = $nPreDel + 1; start with number folllowing $nPreDel eg 1 + 1
    
;   MsgBox(4096, "Format", $nLength & @CRLF & $nNoDel & @CRLF & $nPreDel & @CRLF & $sDelStr & @CRLF & $sDelValue)
    
    For $nLoop = 0 To $nNoDel - 1
        If StringLen($sDelStr) = 0 Then
            $sDelStr &= StringMid($sDelValue, $nCnt, $nWidth)
        Else
            $sDelStr &= $cChar & StringMid($sDelValue, $nCnt, $nWidth)
        EndIf
    
        $nCnt = $nCnt + $nWidth
    Next
; set up $sNewCurrency
    $sNewCurrency = ""
    If $aCurrency[0] = 1 Then
        If $sHasCSymbol = 0 Then
            $sNewCurrency = $sDelStr
        Else
            If $sHasCSymbol = 1 Then; prefix
                $sNewCurrency = $sSymbol & $sDelStr
            Else
                $sNewCurrency = $sDelStr & $sSymbol; suffix
            EndIf
        EndIf
    Else; there are decimal places
        If $sHasCSymbol = 0 Then
            $sNewCurrency = $sDelStr & $cDecimalChar & $aCurrency[2]
        Else
            If $sHasCSymbol = 1 Then; prefix
                $sNewCurrency = $sSymbol & $sDelStr & $cDecimalChar & $aCurrency[2]
            Else
                $sNewCurrency = $sDelStr & $cDecimalChar & $aCurrency[2] & $sSymbol; suffix
            EndIf
        EndIf       
    EndIf
    
    Return $sNewCurrency
EndFunc  ;==>_StringCurencyFormat

Hope it helps!

Dougie

Link to comment
Share on other sites

heres a little hobbyist's code

Dim $t, $final

$Var = 45678913231

$result = StringSplit($var, "")

For $x = $result[0] to 1 Step -1
    $t = $t +1
    If $t = 4 Then
        $final = "," & $final
        $t = 1
    EndIf
    $final =  $result[$x] & $final
Next

MsgBox(0, "Results", $final)

had to try

8)

NEWHeader1.png

Link to comment
Share on other sites

  • 8 years later...

   I googled "Add commas to a number Autoit", and this is the first post on the list of results. After sitting down for a while and trying to come up with the fastest way possible to do this without using stringformat, since I couldn't figure out how to type the format control, this is what I came up with. I made sure this works with decimal numbers, and tried to get some speed statistics for 1 to 15 digit numbers. Autoit puts larger numbers than that in scientific notation, and I don't know how to format the number differently. It's probably another stringformat trick.

   If you only want the actual function, then just copy what is between func and endfunc. Everything else is just for testing purposes.

   Anyway, here is the code. I made all the variable names 1 letter long because I've found in the past that long variable names can slow a script down, and whoever uses this code will probably just #include the file in their script, so this code won't be read or changed much, and doesn't need easy to read variable names. On my machine, I was able to format 300,000 numbers in 6.11 seconds, which is 49,083 numbers per second. It looks like my nice tab indents won't show here, and the code isn't colored normally after the end of my comments, but Tidy Autoit Source should make this code easier to read.

Opt("MustDeclareVars",1)
#cs This is for testing accuracy
Local $N
For $C = 0 to 14
$N = 10^C
ConsoleWrite(_AddCommas($N & ".85") & @CR)
ConsoleWrite(_AddCommas($N) & @CR)
Next
#CE This is for testing accuracy
#CS This is for testing speed
Local $Timer = TimerInit(), $SMax = 10000
For $S = 1 to $SMax
_AddCommas(1.85)
_AddCommas(1)
_AddCommas(10.85)
_AddCommas(10)
_AddCommas(100.85)
_AddCommas(100)
_AddCommas(1000.85)
_AddCommas(1000)
_AddCommas(10000.85)
_AddCommas(10000)
_AddCommas(100000.85)
_AddCommas(100000)
_AddCommas(1000000.85)
_AddCommas(1000000)
_AddCommas(10000000.85)
_AddCommas(10000000)
_AddCommas(100000000.85)
_AddCommas(100000000)
_AddCommas(1000000000.85)
_AddCommas(1000000000)
_AddCommas(10000000000.85)
_AddCommas(10000000000)
_AddCommas(100000000000.85)
_AddCommas(100000000000)
_AddCommas(1000000000000.85)
_AddCommas(1000000000000)
_AddCommas(10000000000000.85)
_AddCommas(10000000000000)
_AddCommas(100000000000000.85)
_AddCommas(100000000000000)
Next
$Timer = TimerDiff($Timer)/1000
$SMax = 30 * $SMax
ConsoleWrite(_AddCommas($SMax) & " numbers in " & _AddCommas(Round($Timer,2)) & " seconds is " & _AddCommas(Floor($SMax/$Timer)) & " numbers per second." & @CR)
#CE This is for testing speed
Func _AddCommas($N)
Local $D = StringInStr($N,".",2)
If $D Then
Local $E = $D - 4
Else
Local $E = StringLen($N) - 3
EndIf
If $E > 0 Then
Local $S = Mod($E,3)
If $S Then
Local $T = StringLeft($N,$S) & ","
Else
Local $T = ""
EndIf
$S += 1
For $C = $S to $E Step 3
$T &= StringMid($N,$C,3) & ","
Next
$T &= StringMid($N,$E + 1)
Return $T
Else
Return $N
EndIf
EndFunc
Edited by Oscis
Link to comment
Share on other sites

  • Moderators

Oscis,

Welcome to the AutoIt forum. :)

You noticed that this thread has been dormant for nearly 9 years, but you still thought it worth reviving? Not a good idea. :naughty:

Please do not necro-post like this again - just open a new thread and link to the old one if it is absolutely necessary for understanding the problem. We ask you to do this for two main reasons:

 

- 1. The language advances and the functionality might well be included in core or UDF code by now

- 2. The changes in language syntax mean that it is likely that code from more than a couple of years ago may well not run under the current release interpreter without significant modification.

No harm done, but now you know. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

I necroed this thread because it is the first result in Google. Even though it's a very old post, it might point people who simply do a Google search to find what they're looking for in the right direction. What is the longest time a thread can be dormant and replied to without the reply being considered a necro-post? 6 months?

Link to comment
Share on other sites

  • Moderators

Oscis,

I understand your point - but if you open a new thread then that is likely to become the new "first return". ;)

As to when posting becomes inadvisable, we have no fixed term - but 9 years is way over any sensible limit. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...