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
Related
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
both txtfield1 and txtMCLCCurrToEUR are doubles
(originally strings converted to double, both are the values of forex with 5 digits after decimal point)
Dim f1 As Double
txtField2.Text = (Double.TryParse(txtMCLCurrToEUR.Text, f1) / Double.TryParse(txtField1.Text, f1)).ToString("N5")
irrespective of their values, I always end up with 1 in the txtField2.text
I seem to have overlooked something essential, but for the life of me -- I don't see what it could be...
any help would be much appreciated!
You should not use f1 for both conversions, the second one would overwrite the first and the result is always one.
Tryparse has no return value, only a flac vor succeed or not.
Dim f1 As Double
Double.TryParse(txtMCLCurrToEUR.Text, f1)
Dim f2 As Double
Double.TryParse(txtField1.Text, f2)
txtField2.Text = (f1/f2 ).ToString("N5")
Double.TryParse() will return a Boolean value(true/false), true for success and false in case of failure of conversion from string to double. so that if you apply division over Boolean values it will gives you result as either 1 or 0.
You can realize this by running your program by enabling Option Strict On
consider one example:
Dim a = True
Dim b = True
Dim c = CDbl(a) / CDbl(b) ' will gives you output as 1
Where as
Dim a = True
Dim b = False
Dim c = CDbl(a) / CDbl(b) ' will gives you output as -1.#INF
Simply you can do this without using any third variable, like the following.
txtField2.Text = (Val(txtMCLCurrToEUR.Text) / Val(txtField1.Text)).ToString("N5")
Val() will return 0 in case it failed to convert the input string/null
I have got a text box that displays the result of two others multiplied together, before anything is in-putted the box displays NaN, is there a way to have it display "0" or even remain empty before anything multiplied.
Dim thick1 As Double
Dim tb8 As Double
Dim result As Double
thick1 = Val(thickness1.Text)
tb8 = Val(TextBox8.Text)
result = thick1 / tb8
TextBox30.Text = FormatNumber(result, 3)
^ the above code is what I am using for the text box.
Try something like this:
Dim result As Double
Dim thick1 As Double = CDbl(thickness1.Text)
Dim tb8 As Double = CDbl(TextBox8.Text)
If IsNumeric(thick1) AndAlso IsNumeric(tb8) AndAlso tb8 <> 0 Then
result = thick1 / tb8
TextBox30.Text = result.ToString("G3")
End If
Another way, try this:
TextBox30.Text = FormatNumber(result, 3).Tostring("n0")
I think it should displays a 0 even if number is not present (like a NaN string)
MSDN: The Numeric ("N") Format Specifier
If not, then try this else:
TextBox30.Text = FormatNumber(result, 3).ToString("0")
"0" Zero placeholder
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
MSDN: Custom Numeric Format Strings
This would appear to be code in an event or form load that it is automatically running. If the textboxes do not yet have values, then result = thick1 / tb8 will result in Nan (not a Number) because you cannot divide by zero.
Again, assuming an event or something:
If tb8 = 0 then
Exit Sub
else
result = thick1 / tb8
TextBox30.Text = result.ToString("G3")
End if
In addition to dumping VAL for TryParse, consider turning Option Explicit on
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
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