Convert string to decimal to string and back to decimal [duplicate] - vb.net

This question already has answers here:
How to convert numbers between hexadecimal and decimal
(20 answers)
Closed 9 years ago.
I want to convert a string to a decimal then to a string and then to a decimal again.
I tried:
Dim s As String = "0.7655"
CDec(sDec).ToString("0.00") 'results in: 7653,00
CDec(sDec).ToString 'results in: 7648
CDec(sDec).ToString("N") 'results in: 7.653,00
So none of these work!
Is there no easy function to just convert the exact decimal to its string representation again? Seems like too much work for such a simple task!
Preferably without formatting the string, because in that case I seem to know beforehand how many characters the resulting string should have.
After converting it to string, I also want to convert it back to a decimal again.

In your current culture the decimal separator might be a comma instead of a dot. Using the invariant culture will always use the dot:
Dim s As String = "0.7655"
Dim decValue As Decimal = Decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture)
Console.WriteLine(decValue.ToString())

You should be able to acheive your answer by using the Parse method.
Dim s As String = "0.7655"
Dim c As Decimal = Nothing
c = Decimal.Parse(s)
Console.WriteLine(c)
You can then use the ToString method to convert back to a string.

Related

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("," , "."))

Data type confusion... for word with both alphabet and numbers eg. tlc5?

In my code i want to provide inputs which are both alphabet and numbers. Eg- tlc5. What data type should i use for such an input since only integer or only string isn't working?
Without having seen your current code: use string. VBA can convert any number to a string.
e.g.
Dim i as Integer
Dim s as String
i = 2
s = "test" & i
will result in a string "test2". To convert any other data type to a string there is the CStr() function.
If you need to work with a number contained in said string later on, I would suggest you store the number and string in a seperate variables as show above.

converting string date to dd.MM.yyyy format

I am working on vb.net application
am getting date like this :
recevdate = rs("ITIReceiveddate")
my recevdate format is like this : 2/27/2016 month/date/year
i want to convert like this : date.month.year 27.2.2016
so i wrote code like this :
Dim dt as string = DateTime.ParseExact(recevdate, "dd.MM.yyyy", Nothing)
but its getting error ..
What is wrong with my code? how i can rectify this issue?
any help is very appreciable..Thanks
DateTime.ParseExact returns a DateTime, not a string. Your project is setup with the Option Strict set to Off and this enables this kind of automatic conversions. But it is, as usual, a trap waiting to kick on unsuspecting programmers.
To execute correctly you need
Dim recevdate = "2/27/2016"
Dim dt As DateTIme = DateTime.ParseExact(recevdate, "M/d/yyyy", Nothing)
Dim formattedString = dt.ToString("d.M.yyyy")
Console.WriteLine(formattedString)
Notice that you have an error also in your formatted mask for parsing the date. If your date has only one digit for months or one digit for days then you need just one M and one d both on the parsing and in the formatting back to string

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.

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.