|
-
Nov 26th, 2008, 08:42 PM
#1
Thread Starter
Member
[RESOLVED] Trouble with code to round down a number
Hi there,
I obtained code to round down a number to a second non-zero digit. Unfortunately, it doesn't work properly. When dblX is 82.02, I would like to round down this number to 82. Would you have any idea how to modify the code so that I works properly?
Thanks for your help!
Public Function RoundDown2ndDigit(ByVal dblX As Double, Optional ByVal dblStep As Double) As Double
Dim strE As String, dblM As Double
strE = Format(Abs(dblX), "0.0E+0")
dblStep = CDbl("0.1E" & Mid(strE, 5))
dblM = CDbl(strE)
If dblM > Abs(dblX) Then dblM = dblM + dblStep
RoundDown2ndDigit = (Sgn(dblX) * dblM)
End Function
-
Nov 26th, 2008, 08:53 PM
#2
Re: Trouble with code to round down a number
Code:
Private Sub Form_Load()
Dim MyNum As Single
MyNum = 82.02
MsgBox "My number rounded down is " & Int(MyNum)
End Sub
-
Nov 26th, 2008, 09:22 PM
#3
Re: Trouble with code to round down a number
Not sure whether I understand your question on "second non-zero digit".
Try this:
Code:
Public Function RoundDown2ndDigit(ByVal x As Double) As Double
Dim n As Long
n = Int(Log(Abs(x)) / Log(10)) - 1
RoundDown2ndDigit = Fix(x / 10 ^ n) * 10 ^ n
End Function
That will round
82.02 to 82
8.35 to 8.3
123.56 to 120
-0.0345 to -0.034
Instead of using Log(), you also can use:
Code:
Dim s1 As String
s1 = Format(x, "Scientific")
n = CLng(Mid$(s1, InStr(s1, "E") + 1)) - 1
-
Nov 26th, 2008, 09:30 PM
#4
Re: Trouble with code to round down a number
AnHn said, "Not sure whether I understand your question on "second non-zero digit".
------------
Agreed. OP, please be more definitive.
-
Nov 26th, 2008, 09:39 PM
#5
Re: Trouble with code to round down a number
In other words, the poster wants to round from 2 decimal places. Well that’s my interpretation 
This is a zero second digit: 82.00 (of course you would represent this as 82, hence the inference on the non zero)
This is a non zero second digit: 82.02
-
Nov 27th, 2008, 09:14 AM
#6
Thread Starter
Member
Re: Trouble with code to round down a number
Hello,
anhn - thanks very much for the code, it works.
Bruce Fox - thanks for the clarification that I should have put in.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|