I want to convert a thousand separated value to integer but am getting one exception.
double d = Convert.ToDouble("100,100,100");
is working fine and getting d=100100100
int n = Convert.ToInt32("100,100,100");
is getting one format exception
Input string was not in a correct format
Why?
try this:
int i = Int32.Parse("100,100,100", NumberStyles.AllowThousands);
Note that the Parse method will throw an exception on an invalid string, so you might also want to check out the TryParse method as well:
string s = ...;
int i;
if (Int32.TryParse(s, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out i))
{
// if you are here, you were able to parse the string
}
What Convert.ToInt32 is actually calling in your example is Int32.Parse.
The Int32.parse(string) method only allows three types of input: white space, a sign, and digits. In the following configuration [ws][sign]digits[ws] (in brackets are optional).
Since your's contained commas, it threw an exception.
Because you're supposed to specify a string containing a plain integer number (maybe preceded by +/- sign), with no thousands separator. You have to replace the separator befor passing the string to the ToInt32 routine.
You can't have separators, just numbers 0 thru 9, and an optional sign.
http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx
Related
I need to display a number with commas and a decimal point.
Eg:
Case 1 : Decimal number is 432324 (This does not have commas or decimal points).
Need to display it as: 432,324.00.
Not: 432,324
Case 2 : Decimal number is 2222222.22 (This does not have commas).
Need to display it as: 2,222,222.22
I tried ToString("#,##0.##"), but it is not formatting it correctly.
int number = 1234567890;
number.ToString("#,##0.00");
You will get the result 1,234,567,890.00.
Maybe you simply want the standard format string "N", as in
number.ToString("N")
It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).
If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").
Edit: The sizes of the groups between the commas are governed by the
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes
array, given that you don't specify a special format provider.
Try with
ToString("#,##0.00")
From MSDN
*The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.*
I had the same problem. I wanted to format numbers like the "General" format in spreadsheets, meaning show decimals if they're significant, but chop them off if not. In other words:
1234.56 => 1,234.56
1234 => 1,234
It needs to support a maximum number of places after the decimal, but don't put trailing zeros or dots if not required, and of course, it needs to be culture friendly. I never really figured out a clean way to do it using String.Format alone, but a combination of String.Format and Regex.Replace with some culture help from NumberFormatInfo.CurrentInfo did the job (LinqPad C# Program).
string FormatNumber<T>(T number, int maxDecimals = 4) {
return Regex.Replace(String.Format("{0:n" + maxDecimals + "}", number),
#"[" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "]?0+$", "");
}
void Main(){
foreach (var test in new[] { 123, 1234, 1234.56, 123456.789, 1234.56789123 } )
Console.WriteLine(test + " = " + FormatNumber(test));
}
Produces:
123 = 123
1234 = 1,234
1234.56 = 1,234.56
123456.789 = 123,456.789
1234.56789123 = 1,234.5679
Try with
ToString("#,##0.###")
Produces:
1234.55678 => 1,234.556
1234 => 1,234
For Razor View:
$#string.Format("{0:#,0.00}",item.TotalAmount)
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
Your question is not very clear but this should achieve what you are trying to do:
decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");
Then formatted will contain: 3,494,309,432,324.00
All that is needed is "#,0.00", c# does the rest.
Num.ToString("#,0.00"")
The "#,0" formats the thousand separators
"0.00" forces two decimal points
If you are using string variables you can format the string directly using a : then specify the format (e.g. N0, P2, etc).
decimal Number = 2000.55512016465m;
$"{Number:N}" #Outputs 2,000.55512016465
You can also specify the number of decimal places to show by adding a number to the end like
$"{Number:N1}" #Outputs 2,000.5
$"{Number:N2}" #Outputs 2,000.55
$"{Number:N3}" #Outputs 2,000.555
$"{Number:N4}" #Outputs 2,000.5551
string Mynewcurrency = DisplayIndianCurrency("7743450.00");
private string DisplayIndianCurrency(string EXruppesformate)
{
string fare = EXruppesformate;
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo("en-IN");
// string text = string.Format(hindi, "{0:c}", parsed);if you want <b>Rs 77,43,450.00</b>
string text = string.Format(hindi, "{0:N}", parsed); //if you want <b>77,43,450.00</b>
return ruppesformate = text;
}
For anyone looking at this now, and getting the "No overload for method 'ToString' takes 1 argument" when using:
TotalNumber.ToString("N")
My solution has been to use :
TotalNumber.Value.ToString("N")
I often get stuck on this when working directly inside an MVC View, the following wasn't working:
#Model.Sum(x => x.Number).ToString("N")
Whereas this works:
#Model.Sum(x => x.Number).Value.ToString("N")
I have a variable, DifferenceAmt, which is a decimal. It can be either negative or positive. I need to output the value of DifferenceAmt, but without the negative sign if it's negative, as a string. I know how to delete the negative sign by checking first if DifferenceAmt is less than zero, and then doing a substring from the 2nd character if it is, but this seems cumbersome. I've tried converting DifferenceAmt to a UInt64 first,
UInt64 differenceamt = (UInt64)DifferenceAmt;
but I keep getting an error message that the number is too big for a UInt64 (even when it's -10, for example). How can I do this?
There are multiple available ways to do it.
The simplest way is to use absolute value using Math.Abs.
decimal x = -10.53m;
string s = Math.Abs(x).ToString(); // 10.53
Another way is to use custom NumberFormatInfo with empty NegativeSign.
decimal x = -10.53m;
string s = x.ToString(new NumberFormatInfo { NegativeSign = string.Empty }); // 10.53
One more way is to use custom formatter for positive/negative numbers. But you have to specify custom string format in such case. More on this: The ";" Section Separator.
decimal x = -10.53m;
string s = x.ToString("#.##;#.##") // 10.53
Use Math.Abs(DifferenceAmt).ToString(); This will give you the absolute value of the number and remove the negative sign.
Use Math.Abs(differenceAmt) to get the absolute value.
Casting to UInt64 won't work. Your example of -10 is outside the range of UInt64, and it would similarly fail for other Decimal values outside the range of UInt64. It would also have to truncate the value to an integer.
You can use this:
Math.Abs(differenceAmt).ToString();
see this:
http://msdn.microsoft.com/en-us/library/a4ke8e73(v=vs.110).aspx
I'd like to make a program that isn't sensitive to the character , or . as input, in order to make some calculations without thinking about which symbol I should use to separate integer part from fractional part.
The only way i can imagine is to recognize the input string, check if there's a . and replace it with a , as my cultureType only accepts ,.
The problem is that I don't have any idea to make it, can someone help me?
if(inputString.Any(x => x == '.'))
{
inputString = inputString.Replace('.', ',');
}
I'm guessing (it's not in your question) that you're trying to parse a decimal, and the number may have a decimal separator and no thousand separator, and it might be a , and it might be a . A possible heuristic to guess which one it is, is to check the last occurrence of either.
That could be done by
string input = "123.456.496,58"; //or 123,456,789.58
int lastComma = input.LastIndexOf(",");
int lastPeriod = input.LastIndexOf('.');
NumberFormatInfo format = new NumberFormatInfo();
if (lastComma > lastPeriod) {
format.NumberDecimalSeparator = ',';
format.NumberGroupSeparator = '.';
} else {
format.NumberDecimalSeparator = '.';
format.NumberGroupSeparator = ',';
}
double parsed = Double.Parse(intput, format);
this fails when there is a group separator after the decimal separator, and other heurisics could be employed to change it (i.e. if there is only one non-numeric character, that one is the decimal separator. If there are multiple non-numeric special characters, and one of them only occurs once, that is the decimal separator)
In the end parsing a string with an unknown format will require some guesswork.
If you're not trying to parse numbers, but are doing something different entirely, disregard this answer, and pick one of the others.
if (yourString.Contains(".")) { youString = yourString.Replace(".", ","); }
I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');
I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].
Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.
s.Substring(0,d);
You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters