Decimal place VB.NET simple - vb.net

I know that is the simple question but how can i return sum of my variable d with decimal places ?
it's always return me 8, not 8.0. But if my variable will be for examle 4.1 it will return 8.2 how it works with 0 in VB.NET?
Public Shared Sub Main()
Dim d As Decimal = 4.0
Console.WriteLine(d+d)
End Sub

use Decimal.ToString() method while writing to console.

Try something like this, pass the decimal in as a string, or else modify this function, but this should do the trick
Private Function ConvertStringToDec(str As String) As Decimal
Dim temp As String = String.Format(".{0}", str)
Dim d As Decimal
Decimal.TryParse(temp, d)
Return dec
End Function

To expand on David's answer, you can manipulate the output of any string you want by changing the first argument of String.Format. For example, if you want two decimal places you can use:
String.Format("{0:0.00}", d+d)
for three decimal places:
String.Format("{0:0.000}", d+d)
The number before the colon corresponds to the argument number. The numbers after the colon specify the format you want. For example with two arguments using different formats:
String.Format("{0:0.0}, {1:0.00}", d, n)
If you had d=4 and n=2 and you printed this out using the above formatter, you would end up with 4.0 (corresponding to the 0 argument with 0.0 format) and a 2.00 (corresponding to the 1 argument with 0.00 format)
and so on. There are a ton of options, not only for numbers, but for dates and more. Check out this easy-to-read website to understand its use a bit more clearly.
Hope this helps!

Related

How to get TrimEnd() to stop at a specific character

I have a series of percentage values saved in a database that look something like this:
Percentage
_____________
100.00000
50.00000
74.02500
When I display the values to the screen, I'd like to trim unnecessary zeroes from the end of the string along with the decimal point so the above examples become:
Percentage
_____________
100
50
74.025
I'm currently using the following code:
displayVal = rawVal.TrimEnd({"0"c, "."c})
but this code continues to trim after the decimal if there are additional zeroes. I also tried:
displayVal = rawVal.TrimEnd(New String({"0", "."}))
which almost works. It just leaves the decimal point.
Is there a way to do what I want using TrimEnd() or do I need to switch to regex?
As Tim already mentioned in the comments, if the data type in the DB is already some numerical type, it would be best to keep it in that type and then use the appropriate numeric formatting when converting it to a string for output. If, however, the input data is already a string, then that's not an option. In that cast, the simplest option is to just do two trims in series, like this:
Private Function RemoveUnecessaryZeros(input As String) As String
Return input.TrimEnd("0"c).TrimEnd("."c)
End Function
However, that doesn't give you a lot of flexibility, it doesn't remove preceding zeros, and it does nothing to reformat the string using the current culture. If that matters, you could instead parse the value into a numeric type and then use the desired string formatting options to re-output it to a string. For instance:
Private Function RemoveUnecessaryZeros(input As String) As String
Dim result As Double
If Double.TryParse(input, result) Then
Return result.ToString()
Else
Return input
End If
End Function
However, when you do it that way, you may potentially lose precision along the way, depending on the input numbers and the data type you choose to parse it with. If you need more control over the parsing/reformatting and you want to keep it purely in strings so no precision is lost, then you may want to consider using regex. For instance:
Private Function RemoveUnecessaryZeros(input As String) As String
Dim m As Match = Regex.Match(input, "[1-9]\d*(\.([1-9]|0+[1-9])+)?")
If m.Success Then
Return m.Value
Else
Return input
End If
End Function

Convert numeric data from database

In my system default decimal separator is comma.
In database I have written numeric values as strings but in format with decimal separator point.
Now, when I read data from database like this "3.2" with following code I get value 32D!
NumericUpDown1.Value = CDec(reader("myfield"))
Is here any way that I can get decimal value of 3,2 from showed code in described situation?
You know your number is stored as a string in the format "1,23456". You are dealing with a globalization issue, and as such, you could convert the string using the appropriate culture formatting settings.
NumericUpDown.Value is of type Decimal, so I use the function Convert.ToDecimal.
For this example, I'll assume the number being inserted was stored in the database by a Croatian, so I'd use "hr-HR" for the culture name.
Dim myFieldCroatia As String = "1,2345678901234567890123456789"
NumericUpDown1.Value = Convert.ToDecimal(myFieldCroatia, New Globalization.CultureInfo("hr-HR"))
And if it were stored by an American, I'd use "en-US"
Dim myFieldUnitedStates As String = "1.2345678901234567890123456789"
NumericUpDown2.Value = Convert.ToDecimal(myFieldUnitedStates, New Globalization.CultureInfo("en-US"))
As an aside, if you had first converted to Double, and implicitly converted to Decimal, you would have lost any precision past 15 to 17 decimal places. Not sure if it's required, but it's worthy of noting.
See MSDN for a complete list of culture names
Try this.
NumericUpDown1.Value = CDec(reader("myfield"), new NumberFormatInfo() { NumberDecimalSeparator = "," });
More info
NumericUpDown1.Value = Convert.ToDouble(reader("myfield").ToString().Replace("," , "."))
is another way if you don't want to convert to Double then you could use ToDecimal.
If I were you, I wouldn't use the CDec but the Val function instead.
Try this code :
NumericUpDown1.Value = Val(reader("myfield").ToString().Replace("," , "."))

How to convert one data type to another

I am a very novice VB.NET programmer. How do I convert one type to another?
Dim a as String="2"
Dim b as Integer='what?
There are several ways to convert a string to an integer.
You know the string contains a numeric:
Dim b as Integer = Integer.Parse(a)
If it is not a valid integer or contains non numerals, it can crash. Other value types (Decimal, Double) have the same method.
Pretty much the same:
Dim b as Integer= Convert.ToInt32(b)
You dont know if the string is clean or not. For instance this would be used to convert a value from a text box, where the user types "cat" as their age:
If Integer.TryParse(a, b) Then ...
The big difference here is that the return is a Boolean (True or False) telling you whether the parsing went ok. If not (False), tell the user to enter again; else (True) the second param will be the converted value. Date, Double, Decimal etc all have a TryParse method.
This answer provides a more detailed explanation.
Many of the "primitive" data types have several parsing methods that can construct from a string representation.
Check the Parse and TryParse shared methods of Integer.

IsNumeric returns true for strings containing a D character

I had a strange error in a VB6 app this morning and it all stems from the fact that IsNumeric is not working as I expected. Can someone shed some light on why? To me this seems like a bug.
This code displays 4.15877E+62 in a message box:
Dim strMessage As String
strMessage = "0415877D57"
If IsNumeric(strMessage) Then
MsgBox CDbl(strMessage)
Else
MsgBox "not numeric"
End If
I am guessing that the runtime engine is incorrectly thinking that the D is in fact an E?
I think this is a bug though as the exact same code in VB.NET outputs not numeric
Is this a known issue with IsNumeric?
If you check the VB6 docs:
Note Floating-point values can be expressed as mmmEeee or mmmDeee, in which mmm is the mantissa and eee is the exponent (a power of 10). The highest positive value of a Single data type is 3.402823E+38, or 3.4 times 10 to the 38th power; the highest positive value of a Double data type is 1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. Likewise, using E in the same fashion treats the value as a Single data type.
I've been using my own IsNumber function for a long time exactly because of this situation. IsNumeric can also return true for certain money symbols, like this: IsNumeric("$34.20").
My IsNumber function looks like this:
Public Function IsNumber(ByVal Data As String) As Boolean
If Data = "" Then
IsNumber = False
Exit Function
End If
IsNumber = IsNumeric(Data & "e0")
End Function
The idea here is... if there is already an e or d in the data, adding another will cause the data to NOT be numeric using the IsNumeric check. You can easily change this function to only allow for integers by replacing "e0" with ".0e0". Want just positive integers? then use this: IsNumeric("-" & Data & ".0e0")
The only downside of this method is that an empty string normally is not numeric, but when you append "e0" to it, it becomes numeric so you need to add a check for that, like I did in my code.
I suggest making a custom validator. Do you want to allow 0-9 only? What about negatives? Commas? I never cared for Microsoft's implementation, but I understand it.

How do I convert from a string to an integer in Visual Basic?

How do I convert from a string to an integer? Here's what I tried:
Price = CInt(Int(txtPrice.Text))
I took out the Int and I still got an exception.
Use
Convert.toInt32(txtPrice.Text)
This is assuming VB.NET.
Judging by the name "txtPrice", you really don't want an Integer but a Decimal. So instead use:
Convert.toDecimal(txtPrice.Text)
If this is the case, be sure whatever you assign this to is Decimal not an Integer.
You can try it:
Dim Price As Integer
Int32.TryParse(txtPrice.Text, Price)
You can use the following to convert string to int:
CInt(String) for ints
CDec(String) for decimals
For details refer to Type Conversion Functions (Visual Basic).
Please try this, VB.NET 2010:
Integer.TryParse(txtPrice.Text, decPrice)
decPrice = Convert.ToInt32(txtPrice.Text)
From Mola Tshepo Kingsley (WWW.TUT.AC.ZA)
Convert.ToIntXX doesn't like being passed strings of decimals.
To be safe use
Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))
You can try these:
Dim valueStr as String = "10"
Dim valueIntConverted as Integer = CInt(valueStr)
Another example:
Dim newValueConverted as Integer = Val("100")
Use Val(txtPrice.text)
I would also allow only number and the dot char by inserting some validation code in the key press event of the price text box.
If there might be invalid characters in the textbox it will throw an exception. The Val command pulls numbers and strips invalid characters. It returns a double. So you want to convert the result of Val to whatever type you need.
Price = Convert.toInt32(Val(txtPrice.Text))
This will return 0 instead of throwing an error on invalid input. If that isn't desired you should be checking that the input is valid before you convert.