Jump to content

Formatting Currency


Recommended Posts

Hey,

I have looked about on quite a few threads and in the help file and i cant seem to find anything that will format to currency. I want to be able to add numbers and have them stick to 2 decimal places. For example by default if i add 0.80 to 0.00 it will return a value of 0.8 when i would want it to be 0.80. Please could someone point me in the right direction and give me an example code if possible :oops:.

Thanks.

Link to comment
Share on other sites

Hello Venix,

I may be wrong, however, I don't believe there is anything native to return a number in currency form. I ran across the same dilemma a few months back and created a function of my own to convert into currency for me. The only drawback is that the return will be treated like a string rather than a number. However when using Number() will convert the string back into number for mathematical needs, and just call it back through the custom currency function before sending to display. Here is the function I wrote. I have not fully tested every number that could be thrown at it, however, it has had some good use and has not failed me yet. Hope it helps and maybe you could draw up a better solution from it. Happy Coding!

Local $amount = _Currency( '1.1')
Local $amount2 = _Currency( 1 )

MsgBox( '', '', $amount & @CRLF & $amount2 )

Func _Currency( $iCurrency )
    If StringInStr( $iCurrency, '.' ) Then
        If StringLen( StringTrimLeft( $iCurrency, StringInStr( $iCurrency, '.' ) ) ) < 1 Then
            Return( StringLeft( $iCurrency, StringInStr( $iCurrency, '.' ) ) & 00 )
        ElseIf StringLen( StringTrimLeft( $iCurrency, StringInStr( $iCurrency, '.' ) ) ) < 2 Then
            Return( StringLeft( $iCurrency, StringInStr( $iCurrency, '.' )+1 ) & 0 )
        ElseIf StringLen( StringTrimLeft( $iCurrency, StringInStr( $iCurrency, '.' ) ) ) > 2 Then
            If StringLeft( StringTrimLeft( $iCurrency, StringInStr( $iCurrency, '.' )+2 ), 1 ) >= 5 Then ;round to nearest cent
                $iCurrency = Number( $iCurrency) + 0.01
            EndIf
            Return( StringLeft( $iCurrency, StringInStr( $iCurrency, '.' )+2 ) )
        Else
            Return( $iCurrency )
        EndIf
    ElseIf IsInt( $iCurrency ) Then
        Return( $iCurrency & '.00' )
    Else
        Return 0
    EndIf
EndFunc

My Contributions: Unix Timestamp: Calculate Unix time, or seconds since Epoch, accounting for your local timezone and daylight savings time. RegEdit Jumper: A Small & Simple interface based on Yashied's Reg Jumper Function, for searching Hives in your registry. 

Link to comment
Share on other sites

This will write in your console: "€1.00 = $1.32" or how ever low the USD is at time of reading.

#include <INet.au3>
$i = _GetCurrentValue('USD', 'EUR')
ConsoleWrite(@CRLF & '€'&StringFormat("%#.2f", 1, 2) & ' = $' & StringFormat("%#.2f", $i, 2) & @CRLF)



Func _GetCurrentValue($sCurrencyOut, $sCurrencyIn)
    Local $a = StringSplit(_INetGetSource('http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=' & $sCurrencyIn & $sCurrencyOut&'=x'), ',')
    If @error Or UBound($a) <> 5 Then Return SetError(1, 0, 0)
    Return $a[2]
EndFunc   ;==>_GetCurrentValue

So to awnser the question use: where $sValue is the ammount you want to have displayed

StringFormat("%#.2f", $sValue, 2)
Edited by Djarlo
Link to comment
Share on other sites

  • Moderators

GellpycleCymn,

Very useful first post - I hope they get better from now on. :oops:

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

Try this one, very easy.

$Amt is the dollar amount and $Num is the formatted amount, so $ret[5] is what you want.

$ret=DllCall("kernel32.dll","int","GetCurrencyFormat","int",0,"int",0,"str",$Amt,"int",0,"str",$Num,"int",20)
Link to comment
Share on other sites

  • 4 years later...
On 04.04.2012 at 4:40 PM, xroot said:

Try this one, very easy.

$Amt is the dollar amount and $Num is the formatted amount, so $ret[5] is what you want.

 

 

$ret=DllCall("kernel32.dll","int","GetCurrencyFormat","int",0,"int",0,"str",$Amt,"int",0,"str",$Num,"int",20)

I don't understand what is the use of a variable here. Can you explain detailed?

$Num

Link to comment
Share on other sites

; https://msdn.microsoft.com/en-us/library/windows/desktop/dd318083(v=vs.85).aspx

;Locale [in]
Global Const $LOCALE_CUSTOM_DEFAULT = 0x0C00
Global Const $LOCALE_CUSTOM_UI_DEFAULT = 0x1400
Global Const $LOCALE_CUSTOM_UNSPECIFIED = 0x1000
Global Const $LOCALE_INVARIANT = 0x007F
Global Const $LOCALE_SYSTEM_DEFAULT = 0x0800
Global Const $LOCALE_USER_DEFAULT = 0x0400

Local $iNumber = 123456.789 ; € 123.456,79
ConsoleWrite(_WinAPI_GetCurrencyFormat($LOCALE_USER_DEFAULT, $iNumber) & @CRLF)

Func _WinAPI_GetCurrencyFormat($LCID, $iNumber, $tCURRENCYFMT = 0)
    Local $Return = DllCall('kernel32.dll', 'int', 'GetCurrencyFormatW', 'ulong', $LCID, 'dword', 0, 'wstr', $iNumber, 'ptr', DllStructGetPtr($tCURRENCYFMT), 'wstr', '', 'int', 2048)
    If @error Or Not $Return[0] Then Return SetError(1, 0, 0)
    Return $Return[5]
EndFunc   ;==>_WinAPI_GetCurrencyFormat

 

Nothing is so strong as gentleness. Nothing is so gentle as real strength

 

Link to comment
Share on other sites

I use this... (found somewhere in this forum:

Local $amount = _Currency( '1.1')
Local $amount2 = _Currency( 1 )

MsgBox( '', '', $amount & @CRLF & $amount2 )

Func _Currency($iAmnt)
    Return _ThouSep(StringFormat("%.2f", $iAmnt))
EndFunc

Func _ThouSep($sText, $Sep = " ", $Dec = ".")
    If Not StringIsInt($sText) And Not StringIsFloat($sText) Then Return SetError(1, 0, $sText)
    Local $aSplit = StringSplit($sText, "-" & $Dec)
    Local $iInt = 1
    Local $iMod
    If Not $aSplit[1] Then
        $aSplit[1] = "-"
        $iInt = 2
    EndIf
    If $aSplit[0] > $iInt Then
        $aSplit[$aSplit[0]] = "." & $aSplit[$aSplit[0]]
    EndIf
    $iMod = Mod(StringLen($aSplit[$iInt]), 3)
    If Not $iMod Then $iMod = 3
    $aSplit[$iInt] = StringRegExpReplace($aSplit[$iInt], '(?<=\d{' & $iMod & '})(\d{3})', $Sep & '\1')
    $sText = $aSplit[1]
    For $i = 2 To $aSplit[0]
        $sText &= $aSplit[$i]
    Next
    Return $sText
EndFunc   ;==>_ThouSep

.. gives me a more choice 

@Terenz, nice snippet, it's going in my toolbox :dance:

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...