Round up to the nearest multiple of a number - vba

This question has already been asked for the C++ language but I need a function for VBA. I tried converting the C++ function to VBA, but it doesn't return the right values.
I need a function that does the following:
RoundUp(23.90, 5)
'return 25
RoundUp(23.90, 10)
'return 30
RoundUp(23.90, 20)
'return 40
RoundUp(23.90, 50)
'return 50
RoundUp(102.50, 5)
'return 105
RoundUp(102.50, 20)
'return 120
Here's what I have so far. It works most of the time, but returns incorrect values for numbers that are less than .5 less than the multiple. So the problem seems to be a rounding problem with how I'm calculating the remainder value.
Public Function RoundUp(dblNumToRound As Double, lMultiple As Long) As Double
Dim rmndr As Long
rmndr = dblNumToRound Mod lMultiple
If rmndr = 0 Then
RoundUp = dblNumToRound
Else
RoundUp = Round(dblNumToRound) + lMultiple - rmndr
End If
End Function
For Example:
RoundUp(49.50, 50)
'Returns 49.50 because rmndr = 0

I'd simply divide by the lMultiple, round up and multiply again.
Assuming you indeed always want to round up (also for negative numbers):
Public Function RoundUp(dblNumToRound As Double, lMultiple As Long) As Double
Dim asDec as Variant
Dim rounded as Variant
asDec = CDec(dblNumToRound)/lMultiple
rounded = Int(asDec)
If rounded <> asDec Then
rounded = rounded + 1
End If
RoundUp = rounded * lMultiple
End Function
I'm not actually a VBA programmer, so this might need a tweaked comma or two. However the important thing is:
Use Decimal (variant subtype) for precision
Let VB do the math for you

Worth trying WorksheetFunction.Ceiling method (Excel)
WorksheetFunction.Ceiling(27.4,5)
Above example will return 30. Here is Link:
https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.ceiling

A far simpler solution is to add .5 to the number before rounding:
1.1 -> Round(1.1+.5, 0) -> 2

Related

Vb.net how to get the number after decimal places

in Vb.net how to get the number after decimal places.
I tried below code.
Dim number As Decimal = 143.500
Dim wholePart As Integer = Decimal.Truncate(number)
Dim fractionPart As Decimal = number - wholePart
Dim secondPart3 As Integer
secondPart3 = Replace(fractionPart, "0.", "0")
then the result is coming 500, but when i tried 143.050 its giving 50 it should show 050
Thanks
Thanks everyone. i got it with sample below code
Dim numar As Double
If Double.TryParse(TextBox1.Text, numar) Then
Dim rmndr As Double
rmndr = numar Mod 1
If rmndr = 0 Then
Else
TextBox2.Text = Split(CStr(TextBox1.Text), ".")(1)
End If
End If
Your solution (here) is unnecessarily complex. You were on the right track in your original post, but conflated numeric values with formatted string values. Because while 050 are 50 are the same numeric value, when you implicitly call ToString on the value (or explicitly with the wrong formatting) then you would always get 50 because the prefixing 0 is unnecessary when working with numeric values.
What you should do is:
Get the integral digits of the decimal value
Convert the underlying decimal value to a String
(optionally) Format the String specifying the level of precision
Drop the integral digits off converted string
Here is an example:
Private Function GetFractionalDigits(value As Decimal) As String
Dim integralDigits = Decimal.Truncate(value)
Return value.ToString().Remove(0, integralDigits.ToString().Length + 1)
End Function
Private Function GetFractionalDigits(value As Decimal, precisionSpecifier As Integer) As String
If (precisionSpecifier < 0) Then
Throw New ArgumentOutOfRangeException("precisionSpecifier", "precisionSpecifier cannot be less than 0")
End If
Dim integralDigits = Decimal.Truncate(value)
Return value.ToString("N" & precisionSpecifier).Remove(0, integralDigits.ToString().Length + 1)
End Function
Fiddle: https://dotnetfiddle.net/SBOXG0

How to multiply all the values of a column?

I've a DataGridView like this layout:
I would like to find a way to multiply all values of the column "Quota", in particular, I wrote a code like this:
If MetroGrid1.Rows.Count > 0 Then
If MetroGrid1.Columns.Contains("Quota") Then
Dim CostTotal As Decimal = MetroGrid1.Rows.Cast(Of DataGridViewRow) _
.Select(
Function(x)
Return CDec(x.Cells("Quota").Value)
End Function
).Sum
Dim risultato = CostTotal * giocata
The problem is that the only mode available is the sum and average, but there is no multiplication. I would like to find a way to replace .Sum with some command that allows me to multiply or totally change the algorithm if necessary.
To multiply every cell as you go through the grid you can loop through multiplying the values and adding it to a variable... First we'll make sure there is a value and if so lets try and cast that value as a double. If so multiply the old values with the new one and so on...
Dim dblTotal As Double = 0
Dim dblValue As Double = 0
For i As Integer = 0 To MetroGrid1.Rows.Count - 1
If MetroGrid1.Rows(i).Cells("Quota").Value IsNot DBNull.Value Then
If Double.TryParse(MetroGrid1.Rows(i).Cells("Quota").Value.ToString, dblValue) Then
dblTotal *= dblValue
End If
End If
Next

Mod with Doubles

Am I doing something wrong or does the VBA Mod operator actually not work with floating point values like Doubles?
So I've always sort of assumed that the VBA Mod operator would work with Doubles based on the VB documentation, but in trying to figure out why my rounding function doesn't work, I found some unexpected Mod behavior.
Here is my code:
Public Function RoundUp(num As Double, Optional nearest As Double = 1)
RoundUp = ((num \ nearest) - ((num Mod nearest) > 0)) * nearest
End Function
RoundUp(12.34) returns 12 instead of 13 so I dug a little deeper and found that:
12.5 Mod 1 returns 0 with the return type of Long, whereas I had expected 0.5 with a type of Double.
Conclusion
As #ckuhn203 points out in his answer, according to the VBA specification,
The modulus, or remainder, operator divides number1 by number2
(rounding floating-point numbers to integers) and returns only the
remainder as result.
And
Usually, the data type of result is a Byte, Byte variant, Integer,
Integer variant, Long, or Variant containing a Long, regardless of
whether or not result is a whole number. Any fractional portion is
truncated.
For my purposes, I need a floating point modulo and so I have decided to use the following:
Public Function FMod(a As Double, b As Double) As Double
FMod = a - Fix(a / b) * b
'http://en.wikipedia.org/wiki/Machine_epsilon
'Unfortunately, this function can only be accurate when `a / b` is outside [-2.22E-16,+2.22E-16]
'Without this correction, FMod(.66, .06) = 5.55111512312578E-17 when it should be 0
If FMod >= -2 ^ -52 And FMod <= 2 ^ -52 Then '+/- 2.22E-16
FMod = 0
End If
End Function
Here are some examples:
FMod(12.5, 1) = 0.5
FMod(5.3, 2) = 1.3
FMod(18.5, 4.2) = 1.7
Using this in my rounding function solves my particular issue.
According to the VB6/VBA documentation
The modulus, or remainder, operator divides number1 by number2
(rounding floating-point numbers to integers) and returns only the
remainder as result. For example, in the following expression, A
(result) equals 5. A = 19 Mod 6.7 Usually, the data type of result is
a Byte, Byte variant, Integer, Integer variant, Long, or Variant
containing a Long, regardless of whether or not result is a whole
number. Any fractional portion is truncated. However, if any
expression is Null, result is Null. Any expression that is Empty is
treated as 0.
Remember, mod returns the remainder of the division. Any integer mod 1 = 0.
debug.print 12 mod 1
'12/1 = 12 r 0
The real culprit here though is that vba truncates (rounds down) the double to an integer before performing the modulo.
?13 mod 10
'==>3
?12.5 mod 10
'==>2
debug.print 12.5 mod 1
'vba truncates 12.5 to 12
debug.print 12 mod 1
'==> 0
I believe that the Mod operator calculates with long type only. The link that you provided is for VB.Net, which is not the same as the VBA you use in MSAccess.
The operator in VBA appears to accept a double type, but simply converts it to a long internally.
This test yielded a result of 1.
9 Mod 4.5
This test yielded a result of 0.
8 Mod 4.5
As a work around your can do some simple math on the values. To get two decimal of precision just multiply the input values by 100 and then divide the result by 100.
result = (123.45*100 Mod 1*100)/100
result = (12345 Mod 100)/100
result = 0.45
I'm late to the party, but just incase this answer is still helpful to someone.
Try This in VBS:
Option Explicit
Call Main()
Sub Main()
WScript.Echo CStr(Is_Rest_Of_Divide_Equal_To_Zero(506.25, 1.5625))
End Sub
Function Is_Rest_Of_Divide_Equal_To_Zero(Divident, Divisor)
Dim Result
Dim DivideResult
If Divident > Divisor Then
DivideResult = Round(Divident/Divisor, 0)
If (DivideResult * Divisor) > Divident Then
Result = False
ElseIf (DivideResult * Divisor) = Divident Then
Result = True
ElseIf (DivideResult * Divisor) < Divident Then
Result = False
End If
ElseIf Divident = Divisor Then
Result = True
ElseIf Divident < Divisor Then
Result = False
End If
Is_Rest_Of_Divide_Equal_To_Zero = Result
End Function
Public Function Modi(d as double) as double
Modi = d - Int(d)
End Function
Dim myDoule as Double
myDoule = 1.99999
Debug.Print Modi(myDoule)
0.99999

Decimal places in a number in VB.NET

How do I check how many decimal places a number has in VB.NET?
For example: Inside a loop I have an if statement and in that statement I want to check if a number has four decimal places (8.9659).
A similar approach that accounts for integer values.
Public Function NumberOfDecimalPlaces(ByVal number As Double) As Integer
Dim numberAsString As String = number.ToString()
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
If indexOfDecimalPoint = -1 Then ' No decimal point in number
Return 0
Else
Return numberAsString.Substring(indexOfDecimalPoint + 1).Length
End If
End Function
Dim numberAsString As String = myNumber.ToString()
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
Dim numberOfDecimals As Integer = _
numberAsString.Substring(indexOfDecimalPoint + 1).Length
Public Shared Function IsInSignificantDigits(val As Double, sigDigits As Integer)
Dim intVal As Double = val * 10 ^ sigDigits
Return intVal = Int(intVal)
End Function
For globalizations ...
Public Function NumberOfDecimalPlaces(ByVal number As Double) As Integer
Dim numberAsString As String = number.ToString(System.Globalization.CultureInfo.InvariantCulture)
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
If (indexOfDecimalPoint = -1) Then ' No decimal point in number
Return 0
Else
Return numberAsString.Substring(indexOfDecimalPoint + 1).Length
End If
End Function
Some of the other answers attached to this question suggest converting the number to a string and then using the character position of the "dot" as the indicator of the number of decimal places. But this isn't a reliable way to do it & would result in wildly inaccurate answers if the number had many decimal places, and its conversion to a string contained exponential notation.
For instance, for the equation 1 / 11111111111111111 (one divided by 17 ones), the string conversion is "9E-17", which means the resulting answer is 5 when it should be 17. One could of course extract the correct answer from the end of the string when the "E-" is present, but why do all that when it could be done mathematically instead?
Here is a function I've just cooked up to do this. This isn't a perfect solution, and I haven't tested it thoroughly, but it seems to work.
Public Function CountOfDecimalPlaces(ByVal inputNumber As Variant) As Integer
'
' This function returns the count of deciml places in a number using simple math and a loop. The
' input variable is of the Variant data type, so this function is versatile enougfh to work with
' any type of input number.
'
CountOfDecimalPlaces = 0 'assign a default value of zero
inputNumber = VBA.CDec(inputNumber) 'convert to Decimal for more working space
inputNumber = inputNumber - VBA.Fix(inputNumber) 'discard the digits left of the decimal
Do While inputNumber <> VBA.Int(inputNumber) 'when input = Int(input), it's done
CountOfDecimalPlaces = CountOfDecimalPlaces + 1 'do the counting
inputNumber = inputNumber * 10 'move the decimal one place to the right
Loop 'repeat until no decimal places left
End Function
Simple...where n are the number of digits
Dim n as integer = 2
Dim d as decimal = 100.123456
d = Math.Round(d, n);
MessageBox.Show(d.ToString())
response: 100.12

Split a 'Decimal' in VB.NET

I am sure this is a very simple problem, but I am new to VB.NET, so I am having an issue with it.
I have a Decimal variable, and I need to split it into two separate variables, one containing the integer part, and one containing the fractional part.
For example, for x = 12.34 you would end up with a y = 12 and a z = 0.34.
Is there a nice built-in functions to do this or do I have to try and work it out manually?
You can use Math.Truncate(decimal) and then subtract that from the original. Be aware that that will give you a negative value for both parts if the input is decimal (e.g. -1.5 => -1, -.5)
EDIT: Here's a version of Eduardo's code which uses decimal throughout:
Sub SplitDecimal(ByVal number As Decimal, ByRef wholePart As Decimal, _
ByRef fractionalPart As Decimal)
wholePart = Math.Truncate(number)
fractionalPart = number - wholePart
End Sub
(As Jon Skeet says), beware that the integer part of a decimal can be greater than an integer, but this function will get you the idea.
Sub SlipDecimal(ByVal Number As Decimal, ByRef IntegerPart As Integer, _
ByRef DecimalPart As Decimal)
IntegerPart = Int(Number)
DecimalPart = Number - IntegerPart
End Sub
Use the Jon version if you are using big numbers.
Simply:
DecimalNumber - Int(DecimalNumber)
Fractional and decimal part of a number have different significance when a number is above zero or below zero. Therefore, you have to consider both cases.
I suggest using the below code:
Dim dbl as double = 13.067
Dim int1 As Integer = 0
Dim fraction As Double = 0
If dbl >= 0 Then
int1 = Math.Floor(dbl)
ElseIf dbl < 0 Then
int1 = Math.Ceiling(dbl)
End If
fraction = dbl - int1
fraction holdes 0.067, and int1 holds 13 .
Floor and Ceiling, round any fractional number to the lowest, and highest consecutive integer, respectively.