Parsing a string - c#

I want to parse a string to long the value is 1.0010412473392E+15.But it gives a exception input string was not in a correct format.how to do this.
Both these answers work how to select both of them as answer.

Check out the System.Globalization.NumberStyles enumeration in the appropriate overload of Int64.Parse. If you specify System.Globalization.NumberStyles.Any, it should work:
long v = Int64.Parse(s, System.Globalization.NumberStyles.Any);
Note, however that the number you are parsing has limited precision, (there are only 13 decimal places but is specified as E+15). Also, the 'Any' enumeration is probably more than you really need - in this case you only need AllowDecimalPoint and AllowExponent:
long v = Int64.Parse(s, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowExponent);

Are you sure you don't want to parse to double?
var myDouble = double.Parse(myString);
You can then try converting to long.
var myLong = Convert.ToInt64(myDouble);

Related

C# parse int from different locale [duplicate]

This question already has answers here:
Thousand separated value to integer
(4 answers)
Closed 3 years ago.
I know, there are other questions like this
e.g. Convert number into culture specific
But I am having a hard time and even the answer doesn't work for me. Still getting
System.FormatException: 'Input string was not in a correct format.'
My current/system locale is de and I am parsing an en int. Whatever I tried so far (including answers from previous quesions, does not work.
So, what am I missing?
string numberStr = "1,111"; // one thousand one hundred eleven
//int result = int.Parse(numberStr);
//int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en-US").NumberFormat);
//int result = int.Parse(numberStr, CultureInfo.InvariantCulture);
//int result = int.Parse(numberStr, CultureInfo.InvariantCulture.NumberFormat);
//int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en-UK").NumberFormat);
int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en"));
Console.WriteLine(result);
Your problem is simply that int.Parse(string) and int.Parse(string, IFormatProvider) don't allow a thousands separator.
You can see this in the Remarks section of the doc:
The s parameter contains a number of the form:
[ws][sign]digits[ws]
You can however, use the int.Parse(string, NumberStyles), overload, which lets you specify NumberStyles.
If we peek at the source for int.Parse(string), we can see that it effectively calls int.Parse(string, NumberStyles.Integer).
If you look at the docs for NumberStyles, we want Integer, but also AllowThousands. We don't want to go as far as Number, because that includes AllowDecimalPoint, and integers can't have decimal points.
int result = int.Parse("1,111", NumberStyles.Integer | NumberStyles.AllowThousands);
You probably also want to specify a culture, because the thousands separator depends on culture (e.g. German uses . as the thousands separator). The invariant culture uses ,, as does en:
int result = int.Parse(
"1,111",
NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture);
If you allow thousands separators, it will work:
int.Parse("1,111", NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("en"));
// 1111

Format a string like you would a numeric value

I have a string that I would like to format the same way I would a numeric value.
Ex:
int num = 2;
string option = num.ToString("000");
Console.WriteLine(option);
//output
//002
But the only way I can think to format it is to parse it as an int, then apply the ToString("000") method to it.
string option = "2";
option = int.Parse(option).ToString("000");
Is there a better, more direct way to do this?
No, there is no built-in mechanism to "format" a string as if it were a number. Some options:
Use string functions (Pad, Length, Substring) to determine what characters should be added
Parse to a numeric type and use ToString with numeric formatting strings
Use a reqular expression to extract the digits and generate a new string
There's not one "right" answer. Each has risks and benefits in terms of safety (what if the string does not represent a valid integer?), readability, performance, etc.
Would this suit your requirement?
string x = "2";
string formattedX = x.PadLeft(3, '0');
Console.WriteLine(formattedX); //prints 002

How to convert string to decimal with 3 decimal places?

string num = 23.6;
I want to know how can I convert it into decimal with 3 decimal places
like
decimal nn = 23.600
Is there any method?
I try my best..
First of all your string num = 23.6; won't even compile. You need to use double quotes with your strings like string num = "23.6";
If you wanna get this as a decimal, you need to parse it first with a IFormatProvider that have . as a NumberDecimalSeparator like InvariantCulture(if your CurrentCulture uses . already, you don't have to pass second paramter);
decimal nn = decimal.Parse(num, CultureInfo.InvariantCulture);
Now we have a 23.6 as a decimal value. But as a value, 23.6, 23.60, 23.600 and 23.60000000000 are totally same, right? No matter which one you parse it to decimal, you will get the same value as a 23.6M in debugger. Looks like these are not true. See Jon Skeet comments on this answer and his "Keeping zeroes" section on Decimal floating point in .NET article.
Now what? Yes, we need to get it's textual representation as 23.600. Since we need only decimal separator in a textual representation, The "F" Format Specifier will fits out needs.
string str = nn.ToString("F3", CultureInfo.InvariantCulture); // 23.600
There are two different concepts here.
Value
View
you can have a value of 1 and view it like 1.0 or 1.0000 or +000001.00.
you have string 23.6. you can convert it to decimal using var d = decimal.Parse("23.6")
now you have a value equals to 23.6 you can view it like 23.600 by using d.ToString("F3")
you can read more about formatting decimal values
the thing that works for me in my case is num.ToString("#######.###")
A decimal is not a string, it does not display the trailing zeros. If you want a string that displays your 3 decimal places including trailing zeros, you can use string.Format:
decimal nn= 23.5;
var formattedNumber = string.Format("{0,000}", nn);

How do I trim the "0." after I do modulo 1 on a double variable

Hello everyone as the title say I want to trim the "0." after I do modulo 1 on a double variable
Example:
double Number;
Number = Convert.ToDouble(Console.ReadLine()); //12.777
test = Number % 1; //0.777
I want my output to be: 777
only using math with no
string trims and so...
Thank you all !!
and in c# please
That is just a formatting on the ToString. Take a look at all your options here
How about
.ToString(".###");
Without using any string functions!
while(Math.Round(Number-(int)Number,1)!=1)
{
Number=Number/0.1;
if(Number-(int)Number==0)break;//To cover edge case like 0.1 or 0.9
}
NOTE: Number should be of double type!
If I take your question literally, then you do not want the decimal point either, so .ToString(".###") will not get you what you want, unless you remove the first character (which is string manipulation, and you said you don't want that either).
If you want 777 in a numeric variable (not a string), then you can multiply your result by 1000, though I don't know if you'll always have exactly 3 digits after the decimal or not.
The easiest way really is just to use string manipulation. ToString the result without any formatting, then get the substring starting after the decimal. For example:
var x = (.777d).ToString();
var result = x.SubString(x.IndexOf('.') + 1);
You are certainly looking for this:-
.ToString(".###");
As correctly pointed by Marc in comments you should have everything to be in a string, because if you output that 0.777 as it really is stored internally, you'd get 8 random bytes.
Something like this:-
var num = (.777d).ToString();
var result = num.SubString(num.IndexOf('.') + 1);
The most generic way to do this would be:
using System.Globalization;
var provider = NumberFormatInfo.InvariantInfo;
var output = test.ToString(".###", provider)
.Replace(provider.NumberDecimalSeparator, String.Empty);
You can also set the NumberDecimalSeparator on a custom NumberFormatInfo, but if you set it to empty it will throw the exception "Decimal separator cannot be the empty string."

How to Parse a String to Double

Here is my string
20.0e-6
I'm parsing it like
String Ans=Double.Parse("20.0e-6")
Now i'm getting the result like 2E-05
But the required output should be like
0.00002
How to get this?
The result of Double.Parse is a Double, not a string. You need to output a string from the double, using ToString.
You should also use an overload of Double.Parse that has a NumberStyles parameter. Using the Float value allows exponent notation:
string Ans=Double.Parse("20.0e-6", NumberStyles.Float).ToString("0.#####");
If you don't want to risk exceptions (InvlidCastException for example), you can use TryParse:
Double res;
if (Double.TryParse("20.0e-6", NumberStyles.Float,
CultureInfo.InvariantCulture ,res))
{
string Ans = res.ToString("0.#####");
}
It's the same number, but if you want to modify the output of the string, use a formatter on your ToString()
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
So
String Ans=Double.Parse("20.0e-6").ToString("0.0####")
One way to get the result you want is to use String.Format as follow:
double x = 20.0e-6;
string y = string.Format("{0:0.######}",x);
Console.WriteLine(y);
Given your example, this outputs the value 0.00002
EDIT
I've just realised that this is actually the opposite of your question so in the aim of keeping the answer useful i'll add the following:
Given a string, you can parse as double and then apply the same logic as above. Probably not the most elegant solution however it offers another way to get the result you want.
string x = "20.0e-6";
var y = double.Parse(p);
Console.WriteLine(String.Format("{0:0.######}",y));

Categories

Resources