Jump to content

Thousand Separator


Recommended Posts

Hello,

Once again, I'd like to ask for some help. I'd like to have 10,000.00 as a result here instead of 100,00.00. What do I need to change?

StringRegExpReplace("10000.00", '(\A\d{1,3}(?=(\d{3})+\z)|\d{3}(?=\d))', '\1,')

The string might change from time to time to 1000.00 or 1000000.00, so it would be great to have this thousand separator all the time.

Thanks!

Edited by NoizeBit
Link to comment
Share on other sites

  • Moderators

NoizeBit,

I still use the old function that was removed a while ago:

;===============================================================================
; Function Name:   _StringAddThousandsSep()
; Description:     Returns the original numbered string with the Thousands and or Decimal delimiter(s) inserted.
; Syntax:          _StringAddThousandsSep($s_string[, $i_convert_lcid = -1[, $i_current_lcid = -1]])
; Parameter(s):    $s_string         - The string to be converted.
;                  $i_convert_lcid   - Optional: Default or -1 wll be the User default locale else:
;                                      LCID of what you want to convert number to.
;                  $i_current_lcid   - Optional: Default or -1 wll be the User default locale else:
;                                      LCID number was converted with originally.
; Requirement(s):
; Return Value(s): - Success - The string with Thousands delimiter added.
;                  - Failure - Returns empty string and sets @error to 1.
; Author(s):       SmOke_N, Valik, GEOSoft

; Modification(s):
; Note(s):    Changes are script breaking after AutoIt version 3.3.0.0
;             LCID numbers can be obtained by pre-pending the OSLang codes in the help file appendix with "0x".
; Example(s):

;===============================================================================

$sRet = _StringAddThousandsSep("10000.00")
ConsoleWrite($sRet & @CRLF)

Func _StringAddThousandsSep($s_string, $i_convert_lcid = -1, $i_current_lcid = -1)
    ; $LOCALE_USER_DEFAULT = 0x0400
    If $i_current_lcid = -1 Or $i_current_lcid = Default Then $i_current_lcid = 0x0400
    If $i_convert_lcid = -1 Or $i_convert_lcid = Default Then $i_convert_lcid = 0x0400

    ; Get lcid decimal and thousands separators
    Local $t_buff_tmp = DllStructCreate("char[4]")
    DllCall("kernel32.dll", "int", "GetLocaleInfo", "int", $i_current_lcid, _
            "int", 0x0E, "ptr", DllStructGetPtr($t_buff_tmp), "int", 4)
    If @error Then Return SetError(1, 0, "")
    Local $s_cur_dec = DllStructGetData($t_buff_tmp, 1)

    DllCall("kernel32.dll", "int", "GetLocaleInfo", "int", $i_convert_lcid, _
            "int", 0x0E, "ptr", DllStructGetPtr($t_buff_tmp), "int", 4)
    If @error Then Return SetError(1, 0, "")
    Local $s_con_dec = DllStructGetData($t_buff_tmp, 1)

    DllCall("kernel32.dll", "int", "GetLocaleInfo", "int", $i_convert_lcid, _
            "int", 0x0F, "ptr", DllStructGetPtr($t_buff_tmp), "int", 4)
    If @error Then Return SetError(1, 0, "")
    Local $s_con_tho = DllStructGetData($t_buff_tmp, 1)

    ; For later formatting
    Local $i_number = StringRegExpReplace($s_string, "(\" & $s_cur_dec & "\d+\z)|(^-|\d+)|(\D)", "$2")
    Local $i_dec = StringRegExpReplace($s_string, "(.+?\" & $s_cur_dec & ")(\d+\z)", "$2")
    If @extended = 0 Then $i_dec = ""

    Local $i_str_len = StringLen($s_string) * 4
    Local $t_numberfmt = DllStructCreate("uint;uint;uint;ptr;ptr;uint")
    Local $t_thousands = DllStructCreate("wchar[2]")
    Local $t_decimal = DllStructCreate("wchar[2]")
    Local $t_buffer = DllStructCreate("wchar[" & $i_str_len & "]")

    DllStructSetData($t_thousands, 1, $s_con_tho)
    DllStructSetData($t_decimal, 1, $s_con_dec)
    DllStructSetData($t_numberfmt, 3, 3)
    DllStructSetData($t_numberfmt, 4, DllStructGetPtr($t_decimal))
    DllStructSetData($t_numberfmt, 5, DllStructGetPtr($t_thousands))
    DllStructSetData($t_numberfmt, 6, 1)

    DllCall("kernel32.dll", "int", "GetNumberFormatW", _
            "int", $i_convert_lcid, "int", 0, _
            "wstr", $i_number, "ptr", DllStructGetPtr($t_numberfmt), _
            "ptr", DllStructGetPtr($t_buffer), "int", $i_str_len)

    If $i_dec = "" Then $s_con_dec = ""
    Return DllStructGetData($t_buffer, 1) & $s_con_dec & $i_dec

EndFunc   ;==>_StringAddThousandsSep

M23

Edited by Melba23

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

There is also a regex version by @AZJIO somewhere on the forum. The thousandth separator is a funny thing, because in some countries a comma (,) represents a decimal character. For example in the UK and USA, 1,000 is one thousand, whereas somewhere else it would be 1.000. Weird isn't it!

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

If I had that need I would end up with something more like:

 

 

msgbox(0, '' , _AddThousandsSep("1000000000.98")) ; default comma
msgbox(0, '' , _AddThousandsSep("10000.00" , ".")) ; specify period
msgbox(0, '' , _AddThousandsSep("1987" , "|")) ; specify pipe


Func _AddThousandsSep($sString , $sSep = ",")

$aString = stringsplit($sString , "." , 2)
$nMax = round(stringlen($aString[0]) / 3)
local $aNum[$nMax]
$sWorking = $aString[0]
$sOut = ""

for $i = 0 to $nMax
    If stringlen($sWorking) > 2 Then
        $sOut = $sSep & stringright($sWorking , 3) & $sOut
        $sWorking = stringtrimright($sWorking , 3)
    Else
        $sOut = ubound($aString) > 1 ? stringright($sWorking , stringlen($sWorking)) & $sOut & "." & $aString[1] : stringright($sWorking , stringlen($sWorking)) & $sOut
        exitloop
    EndIf
next

return $sOut

EndFunc

 

 

 

 

This one may be the dirtiest kind of clean:   *for prices...anything out to the tenths

;~ $sString = "1000000000.98"
;~ $sString = "10000.00"
;~ $sString = "1987"
msgbox(0, '' , stringreverse(stringregexpreplace(stringreverse($sString) , "(\d\d\d)" , "$1,")))

 

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

Is that your version of AZJIO's. If AZJIO's please provide a backlink for attribution.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

There is also a regex version by @AZJIO somewhere on the forum. The thousandth separator is a funny thing, because in some countries a comma (,) represents a decimal character. For example in the UK and USA, 1,000 is one thousand, whereas somewhere else it would be 1.000. Weird isn't it!

Exactly, in my country 1,000.00 would look like 1.000,00 - I'd say annoying at best if you're dealing with currencies all day long ;)

Link to comment
Share on other sites

  • Moderators

NoizeBit,

The function I posted should get that right as it checks for the language settings. All you need to do is set the correct $i_convert_lcid  & $i_current_lcid values and you (should) get the correct separators for that language - certainly worked for me when I tested just now.

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

Really nice Mikell !

Another way, with _WinAPI_CreateNumberFormatInfo :

#include <WinAPILocale.au3>

$sInput = "-1234567890.2244"

$sOutput = _WinAPI_CreateNumberFormatInfo ( StringLen( StringRegExpReplace($sInput, "\d+\.?(.*)", "$1")), 0, 3, ".", ",", 1 )
MsgBox(0, "", _WinAPI_GetNumberFormat(0, $sInput,$sOutput ))

 

Edited by jguinch
Link to comment
Share on other sites

Melba,
"$en" flag = 1 means en notation, 0 means european  :)

$sInput1 = "1234567890,1234"
$sOutput1 = _StringAddThousandsSep($sInput1, 0)
MsgBox(0, "", $sInput1 & @crlf & $sOutput1)

$sInput2 = "-1234567890.1234"
$sOutput2 = _StringAddThousandsSep($sInput2, 1)
MsgBox(0, "", $sInput2 & @crlf & $sOutput2)

Func _StringAddThousandsSep($s_string, $en)
   Return StringRegExpReplace($s_string, '\G(-?\d+?)(?=(\d{3})+(\D|$))', "$1" & Chr($en*44+(not $en)*46))
     ; or this to avoid error checking on the flag
  ; Return StringRegExpReplace($s_string, '\G(-?\d+?)(?=(\d{3})+(\D|$))', "$1" & (($en = 0) ? "," : "."))
EndFunc

Edit

jguinch, what if there are no decimals ?

Edited by mikell
Link to comment
Share on other sites

NoizeBit,

The function I posted should get that right as it checks for the language settings. All you need to do is set the correct $i_convert_lcid  & $i_current_lcid values and you (should) get the correct separators for that language - certainly worked for me when I tested just now.

M23

Thanks Melba, I'll definitely give it a shot, seems like what I'm looking for.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

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