In VB.NET evaluate 0.70 to be equal to .7 - vb.net

I am comparing a value that the user entered into a DataGridView cell - which, coming from an Editing Control will be a string to start with - with a decimal value from the data source (defined as decimal(3,2)).
How can I evaluate a user-entered value of ".7", for example, to be equal to the database value of 0.70?

You can use the CDec function to convert a string value to a decimal. e.g.
If CDec(".7") = 0.7 Then
' This will be true
End If
If you aren't sure that the value entered by the user will be a valid decimal, then you should use Decimal.TryParse:
Dim value As Decimal = 0
If Decimal.TryParse(".7", value) Then
If value = 0.7 Then
' This will be true
End If
End If

Dim str As String = ".7"
Dim test As Double = Double.Parse(str)
MessageBox.Show(test)
You can use Decimal.Parse as indicated by Plutonix as well.

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

Add TextBox strings as numbers

I'm making a counter that updates when the calculate button is pressed, but when I press it it add it like:
11111
where the answer should be 5.
Const tax = 1.05
Dim capPrice = 4.0
Dim espPrice = 2.5
Dim latPrice = 3.5
Dim icedPrice = 3.0
'keeping here teporarily
Dim takeAway = True
If (takeAway = True) Then
capCounter.text = capCounter.text + capAmount.text
espCounter.Text = espCounter.Text + espAmount.Text
latCounter.Text = latCounter.Text + latAmount.Text
icedCounter.Text = icedCounter.Text + icedAmount.Text
What you observe is string concatenation because a TextBox stores strings. You have to convert it to a number, for example with Int32.Parse, then you can sum the values:
Dim capCount As Int32
Dim capAmount as Int32
Dim validCapCount = Int32.TryParse(capCounter.Text, capCount)
Dim validCapAmount = Int32.TryParse(capAmount.Text, capAmount)
If validCapCount AndAlso validCapAmount Then
capCounter.Text = (capCount + capAmount).ToString()
End If
' do the same with the other values ...
This is because the Property Text of a control is a String.
If you want to perform your addition, you must convert those texts to a Integer first :
capCounter.text = (CType(capCounter.text, Integer) + CType(capAmount.text, Integer)).ToString()
(This if you are sure it will only be integers contained in the texts)
If you will use it for numbers only and allow user imput I will recommend you to use a numericUpDown and not a textboxt.
Then you can use the Value property of the numericupdown and it will return a numeric value, not a String.
However, if you need it to be a textbox, use CType as SuperPeanut sugested or TryParse as Tim sugested
Most of the other comments explain most of it, but have you tried using a different type of control to display the information, perhaps a NumericUpDownControl?

VB.NET - DataGridView substring cell for Number(10,2)

I have a DataGridView with a column where the user can insert double. I have to control the cell value before i insert in my database because the table have a number(10,2) datatype for this field.
My current code :
Dim length As Integer = Nothing
Dim row As Integer = DTG.CurrentCell.RowIndex
Dim column As Integer = DTG.CurrentCell.ColumnIndex()
With DTG(row).Cells(column)
length = Len(.Value)
If Not IsNothing(.Value) Then
If Not IsNumeric(.Value) Then
.Value = 0
End If
If length > 10 Then
.Value = .Value.SubString(0, 10)
If .Value.Contains(".") Then
.Value = .Value.SubString(0, 9)
End If
End If
End If
End With
The length method is not appropriate here, because if my cell contains ".", the length increases.
Examples :
1234567891 => length = 10 => insert : 1234567891
123456789.1 => length = 11 => insert : 123456789
In the 2nd case, i need to insert 123456789.1
Can someone advise me ? Thank you
You can use .Value.IndexOf(".") to get the number of digits before the decimal separator (<= 10).
If I'm not mistaken, a database field with a datatype of number(10,2) means that it can carry a maximum value of 99999999.99, using this you might change your code to look like
Dim dbMaxNum As Decimal = 99999999.99
With DTG(row).Cells(column)
If Not IsNothing(.Value) Then
If Not IsNumeric(.Value) Then
.Value = 0
Else
.Value = Math.Min( _
dbMaxNum, _
Math.Round(CDec(.Value), 2, MidpointRounding.AwayFromZero))
End If
End If
End With
Where we first round .Value to two decimal places and then we choose the minimum between the result and the maximum your database field can hold (99999999.99)
The option MidpointRounding.AwayFromZero is to prevent unexpected rounding results, for example 32.625 rounding to 32.62 (an issue that was brought up in this question).
I finally decided to work with the cell value.
If .Value > 99999999.99 Then
.Value = Convert.ToDouble(.Value.SubString(0, 8))
End If
I changed the style format to "N2", so the user can't write more than 2 decimals :
.ValueType = GetType(Double)
.Style.Format = "N2"
I also found another way to do this, i could format my column like a masked textbox. I'll try this solution later.
EDIT :
The previous answer is pretty bad but it had helped me for a while. I found a better way to handle my problem. I created a function that check the number of digits before the decimal, and if the length is higher than 8, its return False :
Public Function numberDigitsBeforeDecimal(ByVal montant As Double) As Boolean
Dim beforeDigit As String = montant.ToString.Substring(0, montant.ToString.IndexOf("."))
If beforeDigit.Length > 8 Then
Return False
Else
Return True
End If
End Function

dividing 2 doubles results always in 1 vb

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

vb.net string contains only 4 digit numbers(or a year)

how can i check if a string only contains 4 digit numbers ( or a year )
i tried this
Dim rgx As New Regex("^/d{4}")
Dim number As String = "0000"
Console.WriteLine(rgx.IsMatch(number)) // true
number = "000a"
Console.WriteLine(rgx.IsMatch(number)) // false
number = "000"
Console.WriteLine(rgx.IsMatch(number)) //false
number = "00000"
Console.WriteLine(rgx.IsMatch(number)) // true <<< :(
this returns false when its less than 4 or at characters but not at more than 4
thanks!
I actually wouldn't use a regex for this. The expression is deceptively simple (^\d{4}$), until you realize that you also need to evaluate that numeric value to determine a valid year range... unless you want years like 0013 or 9015. You're most likely going to want the value as an integer in the end, anyway. Given that, the best validation is probably just to actually try to convert it to an integer right off the bat:
Dim numbers() As String = {"0000", "000a", "000", "00000"}
For Each number As String In numbers
Dim n As Integer
If Integer.TryParse(number, n) AndAlso number.Length = 4 Then
'It's a number. Now look at other criteria
End If
Next
Use LINQ to check if All characters IsDigit:
Dim result As Boolean = ((Not number Is Nothing) AndAlso ((number.Length = 4) AndAlso number.All(Function(c) Char.IsDigit(c))))
You should use the .NET string manipulation functions.
Firstly the requirements, the string must:
Contain exactly four characters, no more, no less;
Must consist of a numeric value
However your aim is to validate a Date:
Function isKnownGoodDate(ByVal input As String) As Boolean 'Define the function and its return value.
Try 'Try..Catch statement (error handling). Means an input with a space (for example ` ` won't cause a crash)
If (IsNumeric(input)) Then 'Checks if the input is a number
If (input.Length = 4) Then
Dim MyDate As String = "#01/01/" + input + "#"
If (IsDate(MyDate)) Then
Return True
End If
End If
End If
Catch
Return False
End Try
End Function
You may experience a warning:
Function isKnownGoodDate does not return a value on all code
paths. Are you missing a Return statement?
this can be safely ignored.