SimpleC Posted August 14, 2013 Posted August 14, 2013 Hello everybody! I'm having trouble with rounding. The program I'm using rounds decimals down. Autoit's round function rounds them up. Example: round(174.126, 2) = 174.13 I need that round to be 174.12. Here's the actually script: #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #Region ### START Koda GUI section ### Form=C:Program FilesAutoinstallForm1.kxf $Form1 = GUICreate("AutoCalc", 227, 200, 15, 15, $WS_EX_TOPMOST) $Button1 = GUICtrlCreateButton("Calculate", 8, 144, 99, 25) $Button2 = GUICtrlCreateButton("Close", 120, 144, 91, 25) $Label4 = GUICtrlCreateLabel("", 72, 136, 4, 4) GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif") $Group1 = GUICtrlCreateGroup("Input", 8, 8, 209, 129) $Label1 = GUICtrlCreateLabel("Rate", 16, 32, 27, 17) $Label2 = GUICtrlCreateLabel("Number of Nights", 16, 64, 86, 17) $Input1 = GUICtrlCreateInput("0.00", 112, 24, 89, 21, BitOR($GUI_SS_DEFAULT_INPUT,$ES_RIGHT)) $Label3 = GUICtrlCreateLabel("Total", 16, 96, 45, 28) GUICtrlSetFont(-1, 11, 400, 0, "MS Sans Serif") $Input2 = GUICtrlCreateInput("1", 112, 56, 89, 21, BitOR($GUI_SS_DEFAULT_INPUT,$ES_RIGHT)) ;$Label5 = GUICtrlCreateLabel("0.00", 136, 96, 39, 28) GUICtrlSetFont(-1, 11, 400, 0, "MS Sans Serif") GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit case $Button1 ;$val = round((((((GUICtrlRead($input1) * .1545) + GUICtrlRead($input1)) + 1.5 + .13) * GUICtrlRead($input2))), 2) $val = (((((GUICtrlRead($input1) * .1545) + GUICtrlRead($input1)) + 1.5 + .13) * GUICtrlRead($input2))) $Label5 = GUICtrlCreateLabel($val, 136, 96, 39, 28) case $Button2 Exit EndSwitch WEnd
Moderators Melba23 Posted August 14, 2013 Moderators Posted August 14, 2013 SimpleC,Interesting. My first thought was to use StringFormat - but that function seems to use Round too: $sRet = StringFormat("%.2f", String(174.126)) MsgBox(0, "Result", $sRet)So it seems you will need to use a wrapper function like this:$nRet = _RoundDown(174.126, 2) MsgBox(0, "Result", $nRet) ; Long version Func _RoundDown($nVar, $iCount) ; Move the decimal point $nMult = $nVar * (10 ^ $iCount) ; Remove remaining decimals $iRound = Int($nMult) ; Move decimal point back again $nRoundDown = Round($iRound / (10 ^ $iCount), $iCount) Return $nRoundDown EndFunc ; Short version Func _RoundDown($nVar, $iCount) Return Round((Int($nVar * (10 ^ $iCount))) / (10 ^ $iCount), $iCount) EndFuncThat seems to work, M23 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 columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area
Starg Posted August 14, 2013 Posted August 14, 2013 (edited) Try this:Round(174.126 - 0.005 , 2) Edit: Melba23 was faster! Edited August 14, 2013 by Starg
BrewManNH Posted August 14, 2013 Posted August 14, 2013 Round by definition will round the number up or down to the nearest number with the specified decimal places. If 5 or above, it will round up, if 0 to 4 will round down. The only thing I can think of would be to take the number, multiply it by 10*(the number of decimal places you want) and then use Intinstead of round, and divide by what you multiplied by. Something like this change to your code. expandcollapse popup#include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #region ### START Koda GUI section ### Form=C:\Program Files\Auto\install\Form1.kxf $Form1 = GUICreate("AutoCalc", 227, 200, 15, 15, $WS_EX_TOPMOST) $Button1 = GUICtrlCreateButton("Calculate", 8, 144, 99, 25) $Button2 = GUICtrlCreateButton("Close", 120, 144, 91, 25) $Label4 = GUICtrlCreateLabel("", 72, 136, 4, 4) GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif") $Group1 = GUICtrlCreateGroup("Input", 8, 8, 209, 129) $Label1 = GUICtrlCreateLabel("Rate", 16, 32, 27, 17) $Label2 = GUICtrlCreateLabel("Number of Nights", 16, 64, 86, 17) $Input1 = GUICtrlCreateInput("0.00", 112, 24, 89, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_RIGHT)) $Label3 = GUICtrlCreateLabel("Total", 16, 96, 45, 28) GUICtrlSetFont(-1, 11, 400, 0, "MS Sans Serif") $Input2 = GUICtrlCreateInput("1", 112, 56, 89, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_RIGHT)) $Label5 = GUICtrlCreateLabel("0.00", 136, 96, 39, 28) GUICtrlSetFont(-1, 11, 400, 0, "MS Sans Serif") GUICtrlCreateGroup("", -99, -99, 1, 1) GUISetState(@SW_SHOW) #endregion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 $Tax = .1545 $Rate = GUICtrlRead($Input1) $LengthStay = GUICtrlRead($Input2) $val = Int(((((($Rate * $Tax) + $Rate) + 1.5 + .136) * $LengthStay)) * 10 ^ 2) / 10 ^ 2 ;~ $val = (((((GUICtrlRead($input1) * .1545) + GUICtrlRead($input1)) + 1.5 + .13) * GUICtrlRead($input2))) GUICtrlSetData($Label5, $val) Case $Button2 Exit EndSwitch WEnd If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag GudeHow to ask questions the smart way! I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from. Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays. - ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script. - Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label. - _FileGetProperty - Retrieve the properties of a file - SciTE Toolbar - A toolbar demo for use with the SciTE editor - GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI. - Latin Square password generator
SimpleC Posted August 14, 2013 Author Posted August 14, 2013 I think Melba's is correct. Thank you for the quick responses!
macargu Posted August 14, 2013 Posted August 14, 2013 Hello everybody! I'm having trouble with rounding. The program I'm using rounds decimals down. Autoit's round function rounds them up. Example: round(174.126, 2) = 174.13 I need that round to be 174.12. Unless I am not understanding something here, but it would seem to me that the program is just trimming off everything after the second digit to the right of the decimal point. To achieve that, I would do the following: $Var = 174.126 ; Splitting the number into its components, using the decimal point as separator: $SplitVar = StringSplit($Var, ".") ; $SplitVar[1]= 174 ; $SplitVar[2]= 126 ; Trimming the decimal component to two digits: $SplitVar[2] = StringLeft($SplitVar[2], 2) ; $SplitVar[2] = 12 ; Joining both components back together $FinalVar = $SplitVar[1] & "." & $SplitVar[2]) ; $FinalVar = 174.12 I hope I am not saying something really stupid!
kylomas Posted August 14, 2013 Posted August 14, 2013 Or more simply ConsoleWrite(stringtrimright(123.1123,1) & @LF) Forum Rules Procedure for posting code "I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals." - Sir Winston Churchill
jchd Posted August 14, 2013 Posted August 14, 2013 (edited) macargu Indeed one can work on the string representation as well, and even make that a one-liner by trimming or as a regexp replacement. But I bet that it would be more costly this way since that involves 2 costly conversions (double <==> string) plus string operation(s). kylomas BTW, trimming needs a bit more caution unless you already know in advance how many positions the decimal part has. Furthermore, it would fail as is on integral values. Pffft, too many edits. Edited August 14, 2013 by jchd This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe hereRegExp tutorial: enough to get startedPCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta. SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)
Moderators Melba23 Posted August 14, 2013 Moderators Posted August 14, 2013 macargu, Welcome to the AutoIt forum. Your suggestion is perfectly valid - there are often several ways of reaching the same destination. Incidentally, the new Beta allows you to do this in just one line: $nVar = 174.126 $nRounded = StringSplit($nVar, ".")[1] & "." & StringLeft(StringSplit($nVar, ".")[2], 2) ConsoleWrite($nRounded & @CRLF) Pretty nifty - if a little complex at first glance. M23 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 columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area
kylomas Posted August 14, 2013 Posted August 14, 2013 @jchd - Yes, you're probably right but AutoIT handles the conversion Ok local $a = 1.55 ConsoleWrite(stringtrimright($a,1) * 2 & @LF) Forum Rules Procedure for posting code "I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals." - Sir Winston Churchill
jchd Posted August 14, 2013 Posted August 14, 2013 Of course it does! I meant from a performance point of view. If you invoke that once in a blue moon, fine. If it's in a tight loop, it might slow things down. This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe hereRegExp tutorial: enough to get startedPCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta. SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)
kylomas Posted August 14, 2013 Posted August 14, 2013 (edited) @jchd - Understood BTW, trimming needs a bit more caution unless you already know in advance how many positions the decimal part has. Furthermore, it would fail as is on integral values. I agree, it's a kludgy solution Edited August 14, 2013 by kylomas Forum Rules Procedure for posting code "I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals." - Sir Winston Churchill
jchd Posted August 14, 2013 Posted August 14, 2013 For strings either Melba's 1-liner or a regexp are fine. But if the user wants strings and a fixed 2-digit decimal part, he has to cope with integers. This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe hereRegExp tutorial: enough to get startedPCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta. SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)
macargu Posted August 14, 2013 Posted August 14, 2013 macargu, Welcome to the AutoIt forum. Your suggestion is perfectly valid - there are often several ways of reaching the same destination. Incidentally, the new Beta allows you to do this in just one line: $nVar = 174.126 $nRounded = StringSplit($nVar, ".")[1] & "." & StringLeft(StringSplit($nVar, ".")[2], 2) ConsoleWrite($nRounded & @CRLF) Pretty nifty - if a little complex at first glance. M23 Thank you, Melba23. I am really glad to see that an experienced coder as yourself used the exact same logic I, a beginner, did, only you did it in a sintactically compact, more efficient and elegant way. What took me 3 rows, you did in one. Very clear, very nice. Macargu
BrewManNH Posted August 14, 2013 Posted August 14, 2013 My solution was a single line as well, and the result is the same. If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag GudeHow to ask questions the smart way! I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from. Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays. - ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script. - Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label. - _FileGetProperty - Retrieve the properties of a file - SciTE Toolbar - A toolbar demo for use with the SciTE editor - GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI. - Latin Square password generator
kylomas Posted August 14, 2013 Posted August 14, 2013 (edited) @BrewmanNH - Nice! Can you explain why this works (math illiterate) local $a = 1.737 ; 1 dec place ConsoleWrite((int($a*10^1)/10^1) * 2 & @LF) ; 2 dec place ConsoleWrite((int($a*10^2)/10^2) * 2 & @LF) kylomas edit: shopping for new fingers that can actually type Edited August 14, 2013 by kylomas Forum Rules Procedure for posting code "I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals." - Sir Winston Churchill
BrewManNH Posted August 14, 2013 Posted August 14, 2013 (edited) Your first example is multiplying the number by 10, removing anything past the decimal point 1.737 * 10 = 17.37, take the integer portion of that, 17, divide by 10 to get 1.7. The second is the same except you're multiplying and dividing by 100 in this case, so you get 1.73. Edited August 14, 2013 by BrewManNH If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag GudeHow to ask questions the smart way! I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from. Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays. - ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script. - Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label. - _FileGetProperty - Retrieve the properties of a file - SciTE Toolbar - A toolbar demo for use with the SciTE editor - GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI. - Latin Square password generator
kylomas Posted August 14, 2013 Posted August 14, 2013 @BrewmanNH - Shifting the decimal and dividing the int, of course (obvious when you see the solution). Thanks for the explanation! Forum Rules Procedure for posting code "I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals." - Sir Winston Churchill
macargu Posted August 14, 2013 Posted August 14, 2013 My solution was a single line as well, and the result is the same. Yes. Very nice solution, BrewManNH. Macargu
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now