How to convert string to int?I know convert.ToInt32 is used.But it fail.Error is input string is not in proper format.
String s1 = "12.00"
I love the assumption that the decimal separator always is a dot (.). You'd better use the InvariantCulture, which contains a NumberFormat that explicitly specifies the dot as a decimal separator:
Convert.ToInt32(Convert.ToDouble("12.00", CultureInfo.InvariantCulture));
To clarify: half the world uses the dot, the other half a comma. When I run this on a PC with a Dutch culture and do not specify a CultureInfo, it takes the system default (comma) and returns 1200, ignoring the dot.
While it does not directly affect your problem, it is something that can't be stressed enough.
error is because string is "12.00"
first convert string to double than in int
int a = Convert.ToInt32(Convert.ToDouble("12.00"));
or
IF you just want integer part of it than
string s= "12.00";
string[] words = s.Split('.');
int a = Convert.ToInt32(words[0]);
Also check already answered threads on SO : C# Convert String Decimal to Int
"12.00" is a decimal number, not an integer. Integers don't have fractional portions. Use Convert.ToDouble or similar to get a floating-point number, or trim off the decimal part of the string (the . and what follows) prior to calling Convert.ToInt32.
The string "12.00" is a double/decimal value. Use Double.Parse() or Double.TryParse() or Convert.ToDouble().
Related
I am trying to format a zero currency value as an empty string, so that when the currency value is 0.00 then an empty string gets displayed rather than $0.00.
This code is part of an ASP.Net app that will display currency value to end user.
I have used following code to achieve this goal.
Question : Is it possible to achieve this by just using {0:C} format string or another version of this format string instead of using if then else coding for this? If I use ###,###,###.## as the data format string then an empty string shows for zero currency value and also I get rid of the if then else coding but for non-zero values no currency symbol shows.
If Double.Parse(Decimal.Parse(CDec(currencyValue))) = 0 Then
charValue = Nothing
Else
charValue = String.Format("{0:C}", CDec(currencyValue))
End If
UPDATE
I ended up using the following code, which is working fine. If is better than IIf because it does short-circuiting, which means that IIf will evaluate all expressions whether the condition is true or false but If will evaluate the first expression only if condition is true and evaluate the second expression only if condition is false.
Dim d As Decimal
Decimal.TryParse(currencyValue, d)
charValue = If(d = 0D, Nothing, String.Format("{0:C}", d))
I don't think there is a way using formatting to display an empty string.
But you can write it like:
charValue = If( currencyValue = 0D, "", currencyValue.ToString("C") )
using the If Operator (Visual Basic).
Also this is something I would not do:
If Double.Parse(Decimal.Parse(CDec(currencyValue))) = 0 Then
If currencyValue is Decimal:
If (currencyValue = 0D) Then
If currencyValue is Double:
If (currencyValue = 0R) Then
Also, if you are using a database and this is a Sql Server mind SQL Server Data Type Mappings
I don't think you can when using C or the other similar standard formats, since they are already defining a culture-specific format that will include a format for zero.
But if you specify your own custom format, you can specify three different formats separated by ;s, one each for positive numbers, negative numbers, and zero, respectively.
For example (giving an empty string for the zero format, resulting in blank zeroes):
charValue = String.Format("{0:#,##0.00;-#,##0.00;""""}", CDec(currencyValue))
And from what I can see, omitting the format for negative gives a default that matches the positive, whereas omitting the format for zero gives blank, which is what you're looking for, so this should be sufficient as well:
charValue = String.Format("{0:#,##0.00;;}", CDec(currencyValue))
(Using whichever custom format you wish.)
UPDATE: You can get the current currency symbol and manually put it into your custom format. IE:
Dim symbol = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol
charValue = String.Format("{0}{1:#,##0.00;;}", symbol, CDec(currencyValue))
From the sound of it, though, I think I would actually recommend doing basically what you started with, maybe with an extension method.
<Extension>
Public Function ToCurrencyString(pValue As Decimal) As String
Return IIf(pValue = 0, "", pValue.ToString("C"))
End Function
Dim someValue As Decimal = 1.23
Console.WriteLine(someValue.ToCurrencyString())
This gives you exactly what you're looking for. The exact same format as C gives, but with blank zeroes.
I have a dropdownlist that has the value of two columns in it... One column is a number ranging from 5 characters long to 8 characters long then a space then the '|' character and another space, followed by a Description for the set of numbers.
An example:
12345678 | Description of Product
In order to pull the items for the dropdownlist into my database I need a to utilize a substring to pull the sequence of numbers out only.
Is it possible to write a substring to pull multiple character lengths? (Sometimes it may be 6 numbers, sometimes 5 numbers, sometimes 8, it would depend on what the user selected from the dropdownlist.)
Use a regular expression for this.
Assuming the number is at the start of the string, you can use the following:
^[0-9]+
Usage:
var theNumbers = RegEx.Match(myDropdownValue, "^[0-9]+").Value;
You could also use string.Split to get the parts separated by | if you know the first part is what you need and will always be numeric:
var theNumbers = myDropdownValue.Split("| ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries)[0];
Either of these approaches will result in a string. You can use int.Parse on the result in order to get an integer from it.
This is how I would do it
string str = "12345678 | Description of Product";
int delimiter;
delimiter = str.IndexOf("|") - 1;
string ID =str.substring(0, delimiter);
string desc = str.substring(delimiter + 1, str.length - 1);
Try using a regex to pull out the first match of a sequence of numbers of any length. The regex will look something like "^\d+" - starts with any number of decimal digits.
Instead of using substring, you should use Split function.
var words = phrase.Split(new string[] {" | "},
StringSplitOptions.RemoveEmptyEntries);
var number = word[0];
I was looking for some RegEx or any other method to convert digits 0-9 into ०-९ (devanagari script). I am using asp.net but could not find any method in globalization namespace which does this.
Any help is greatly appreciated.
Found similar post here!
My solution is bit different though as I know the source and destination culture. So I can hard-code the digits array.
string devYear = "";
string[] devD = { "०", "१", "२", "३", "४", "५", "६", "७", "८", "९" };
char[] digits = curYear.ToCharArray();
foreach (char ch in digits)
{
devYear += devD[int.Parse(ch.ToString())];
}
Another change is that I am iterating through the year digits instead of devD array. Saves few iterations as most numbers will be less than 10 digit. In my case, only four digits.
Hopefully will be useful for someone stuck up on similar lines.
Does each latin digit 0..9 map to exactly a devanagari digit (I do think so, if I understand Wikipedia correctly)=
If yes, how about the following:
public static string ConvertDigits( string s )
{
return s
.Replace("0", "०")
.Replace("1", "१")
.Replace("2", "२")
.Replace("3", "३")
.Replace("4", "४")
.Replace("5", "५")
.Replace("6", "६")
.Replace("7", "७")
.Replace("8", "८")
.Replace("9", "९");
}
For optimization, you could check for string.IsNullOrEmpty() before calling the string.Replace function.
In Addition (if this is suitable for a devanagari digit), call the string.Replace() function overload that takes chars as parameters rather than strings.
I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:
public static string addCommas(string cash) {
return string.Format("{0:n0}", cash).ToString();
}
Where am I going wrong?
Thanks.
Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?
Well, you are sending in a string. it looks like you want a currency back
Why are you passing in a string to the method if it is a numeric value?
String.Format will return a string so there is not need to .ToString() it again.
{0:c} = Currency format if you do not want the $ then use {0:n}
Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash
return String.Format("{0:c}", (decimal)cash);
or
return String.Format("{0:n}", (decimal)cash);
but i think it should be something like:
public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}
but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.
In order to apply number formatting you have to pass cash as a number type (int, double, float etc)
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.
EDIT
Here is the code in its entirety:
static class Program {
static void Main() {
double d = 123456789.7845;
string s = addCommas(d);
System.Console.WriteLine(s);
}
public static string addCommas(double cash) {
return string.Format("${0:#,###0.##}", cash);
}
}
This prints "$123,456,789.78" to console. If you're getting
error CS1502: The best overloaded
method match for 'addCommas(double)'
has some invalid arguments
check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.
i have a method on my custom class to convert any numbers
public static string ConvertToThosandSepratedNumber(object number)
{
string retValue = "";
retValue = string.Format("{0:N0}", Convert.ToDecimal(number));
return retValue;
}
Here is a fairly efficient way to Add commas for thousands place, etc.
It is written in VB.net.
It does not work for negative numbers.
Public Function AddCommas(number As Integer) As String
Dim s As String = number.ToString()
Dim sb As New StringBuilder(16)
Dim countHead As Integer = s.Length Mod 3
If countHead = 0 Then countHead = 3
sb.Append(s.Substring(0, countHead))
For I As Integer = countHead To s.Length - 1 Step 3
sb.Append(","c)
sb.Append(s.Substring(I, 3))
Next
Return sb.ToString()
End Function
i have a double, the decimal place isn't fix (8-?)
i want to fix the decimal place to six (for example: 1,234567).
this is my double:
CStr(score)
i guess it's quiet simple :P
Try this instead:
score.ToString("0.000000")
You can also Math.Round(3.44, 1) 'Returns 3.4.
Math.Round
After Decimal point Add Zero's like this
Dim tot as String
Dim totAmt as Double
totAmt=10.10
tot=String.Format("{0:00.000}", totAmt)
OutPut: 10.100
After Decimal point Remove Zero's like this
totAmt=10.750
tot=Math.Round(totAmt,2)
Output:10.75
Sloved