Jump to content

Rounding decimal down


Recommended Posts

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

Link to comment
Share on other sites

  • Moderators

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)
EndFunc
That seems to work, :)

 

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

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.

#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 Gude
How 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

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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 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 here
RegExp tutorial: enough to get started
PCRE 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)

Link to comment
Share on other sites

  • Moderators

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

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

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 here
RegExp tutorial: enough to get started
PCRE 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)

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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 here
RegExp tutorial: enough to get started
PCRE 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)

Link to comment
Share on other sites

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

Link to comment
Share on other sites

My solution was a single line as well, and the result is the same. :D

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 Gude
How 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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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 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 Gude
How 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

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

×
×
  • Create New...