I want to convert string to double.
Here's example of what I do :
string line = "4.1;4.0;4.0;3.8;4.0;4.3;4.2;4.0;";
double[] values = line2.Split(';').Select(double.Parse).ToArray();
But an error appears
Input string was not in a correct format.
When I try
string line2 = "1;2;3;4;5;6;7;8;9;10;11;12";
double[] values = line2.Split(';').Select(double.Parse).ToArray();
It works perfectly fine.
What should be input format for double values to work ?
Your problem is the last semicolon in the first input. The double.Parse method is being passed an empty string. double value2 = double.Parse(""); There are several ways to fix this, I'll outline two here:
Check if the last character in the input is a semicolon, if so, strip it. (This should be self explanatory.)
Use the StringSplitOptions.RemoveEmptyEntries overload.
I prefer the second option, myself. As this also removes issue with two consecutive semicolons.
string line = "4.1;4.0;4.0;3.8;4.0;;4.3;4.2;4.0;";
double[] values = line.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries).Select(double.Parse).ToArray();
Also, just to humour the idea that it could be a culture issue as well; the following code makes adjustments for culture-specific scenarios. The reason for the if check is to save on compute time. It could be removed if you desire, with no harm to the overall affect. (It simply means that the programme will replace . with . in situations where the programme is run on a computer with a culture set to use decimals for separators. This is merely a simple optimization.)
string line = "4.1;4.0;4.0;3.8;4.0;;4.3;4.2;4.0;";
if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator != ".")
line = line.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
double[] values = line.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries).Select(s => double.Parse(s)).ToArray();
Another sidebar about the potential for a culture issue: if it were a culture issue, the operation would not have thrown an exception, but instead simply return each digit of the number without separator. (I.e. 41, 40, 40, 38, 40, 43, 42, 40)
Other options:
Use double.TryParse instead.
Use a custom for loop and manually parse your data.
There are likely other options as well that I cannot think of.
Another option would be to use the double.TryParse() method on each item in your split array. This will ensure that each item in the array (empty or not) is a valid double before attempting to add it to the values array.
For example:
string line = "4.1;4.0;4.0;3.8;4.0;4.3;4.2;4.0;";
double temp = 0;
double[] values = line.Split(';')
.Where(item => double.TryParse(item, out temp))
.Select(i => temp).ToArray();
Related
I have a date range come like this,
string ActualReleaseDates ="7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
I want to check NewsReleaseDate is inside the ActualReleaseDates
But in the following code it return as a false.
if (ActualReleaseDates.Split(',').Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
//some code here
}
The immediate problem is that after splitting your ActualReleaseDates string, there isn't an entry of "7/11/2016"... instead, there's an entry of " 7/11/2016"... note the space.
But more fundamentally, just trimming the start of NewsReleasedDate won't help if the value is something like "07/08/2016"... what you should be doing is handling these values as dates, rather than as strings:
Split ActualReleaseDates by comma, then parse each value (after trimming whitespace) in an appropriate format (which I suspect is M/d/yyyy) so that you get a List<DateTime>.
Parse NewsReleasedDate in the appropriate format, which I suspect is MM/dd/yyyy, so you get a DateTime.
See whether the parsed value from the second step occurs in the list from the first step.
(I'd personally recommend using Noda Time and parsing to LocalDate values, but I'm biased...)
Fundamentally, you're trying to see whether one date occurs in a list of dates... so make sure you get your data into its most appropriate representation as early as possible. Ideally, avoid using strings for this at all... we don't know where your data has come from, but if it started off in another representation and was converted into text, see if you can avoid that conversion.
The white space problem. You can use trim() and ' 7/11/2016' will be '7/11/2016'
var ActualReleaseDates = "7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
var NewsReleasedDate = "07/11/2016";
var splitActualReleaseDates = ActualReleaseDates.Split(',').Select(x => x.Trim());
if (splitActualReleaseDates.Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
}
You can use linq to convert your strings into DateTime objects and compare them instead of strings
string ActualReleaseDates ="7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
var releaseDates = ActualReleaseDates.Split(',').Select(x => DateTime.Parse(x));
var newsReleased = DateTime.Parse(NewsReleaseDate);
if (releaseDates.Contains(newsReleased))
{
//some code here
}
please note that DateTime is parsed respectively to the current Culture. You can use DateTime.ParseExact if you want to specify exact date format.
You can Prase to DateTime before doing the query like this:
(I think this is the most accurate and guaranteed way to compare dates)
Func<string, DateTime> stringToDate = s => DateTime.ParseExact(s.Trim(), "M/d/yyyy",
CultureInfo.InvariantCulture);
DateTime newReleaseDateTime = stringToDate(NewsReleasedDate);
bool result = ActualReleaseDates.Split(',').Select(x => stringToDate(x))
.Contains(newReleaseDateTime);
It returns false because of the date 07/11/2016 stored in NewsReleasedDate is stored as string with a '0' at the begining. And in the ActualReleaseDates string you have white spaces between the ',' and numbers.
Try to rewrite theese strings like this :
ActualReleaseDates ="7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016"; // white spaces removed.
and the variable like this :
NewsReleasedDate ="7/11/2016"; // 0 removed
This is my code example :
string ActualReleaseDates = "7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate = "7/11/2016";
string[] dates = ActualReleaseDates.Split(',');
Console.WriteLine(dates.Contains(NewsReleasedDate));
This is not the best way to compare dates, you can use Date class which is usefull to do this kind of comparations.
So I have this file with a number that I want to use.
This line is as follows:
TimeAcquired=1433293042
I only want to use the number part, but not the part that explains what it is.
So the output is:
1433293042
I just need the numbers.
Is there any way to do this?
Follow these steps:
read the complete line
split the line at the = character using string.Split()
extract second field of the string array
convert string to integer using int.Parse() or int.TryParse()
There is a very simple way to do this and that is to call Split() on the string and take the last part. Like so if you want to keep it as a string:
var myValue = theLineString.Split('=').Last();
If you need this as an integer:
int myValue = 0;
var numberPart = theLineString.Split('=').Last();
int.TryParse(numberPart, out myValue);
string setting=sr.ReadLine();
int start = setting.IndexOf('=');
setting = setting.Substring(start + 1, setting.Length - start);
A good approach to Extract Numbers Only anywhere they are found would be to:
var MyNumbers = "TimeAcquired=1433293042".Where(x=> char.IsDigit(x)).ToArray();
var NumberString = new String(MyNumbers);
This is good when the FORMAT of the string is not known. For instance you do not know how numbers have been separated from the letters.
you can do it using split() function as given below
string theLineString="your string";
string[] collection=theLineString.Split('=');
so your string gets divided in two parts,
i.e.
1) the part before "="
2) the part after "=".
so thus you can access the part by their index.
if you want to access numeric one then simply do this
string answer=collection[1];
try
string t = "TimeAcquired=1433293042";
t= t.replace("TimeAcquired=",String.empty);
After just parse.
int mrt= int.parse(t);
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."
I'm stuck. (got a thinking barrier right now) :/
I need a stringarray from a string which contaions a lot of "sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."
There are always 8 values in this string. I want each (of these 8 ) values in the array[8].
But most importantly are the value. (the text at the beginning is unnecessary).
Would this work:
var source = "sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."
var result = source.Split(new []{"\n\t\t\t\t"}, StringSplitOptions.None);
that is: guessing that all your values are separated by that newline+4 tabs.
If that is not (always) the separator, then you need to specify how to identify a "value" from a "separator".
I think the following code will do what you need
int i,j;
int[] array=new int[8];
string s="sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."; // or input something
for(i=j=0;i<s.Length;i++){
if (s[i]>='0'&&s[i]<='9'){
array[j++]=s[i]-'0';
}
}
I have a senario where I am converting numbers to words and I have suceeded in it, but I found one scenario where it's not working. If I enter the number as "10", it displays "ten". Also, "10.2" will display "ten point two". However, if I enter "10.0" it will not display as "ten point zero".
For seperating the whole number part from the decimal part I usually split the number by '.', but if I enter a number like "10.0", the string array will contain only "10" and not the "0"
The spitting part which I have done is given below:
string[] number = Convert.ToString(context.NumberToTranslate).Split('.');
To test if your number is an integer w/o decimal point you could try and parse it with
int tmpInt;
bool isInteger = Int32.TryParse(num.ToString(), out tmpInt);
If it is an integer just convert the number to your string representation otherwise preserve the digit after the decimal point no matter what using a custom format string:
string number = num.ToString("#.0");
The same issue can arise if your number is less than 1, so you can use the zero placeholder for the digit before the decimal point as well:
string number = num.ToString("#0.0");
Also see Custom Numeric Format Strings
Actually numbers after point is lost if the number, even i the number is a Float or Double.
The solution is to use decimal Type for these numbers, it preserves the 0 after decimal.
Example:
Console.WriteLine(Convert.ToString(10.0M));
Output:
10.0
Febin:
It seems like an order of operations issue. Try doing the splitting before the converting"
var parts = ("10.0").Split('.'); //or context.NumberToTranslate
parts[0] //"10"
parts[1] //"0"
//Convert
string[] number = Convert.ToString(parts);
You don't have to break it out completely, but I did that to show you can split "10.0" and then do what you want with it.
One thing you could do is compare your number to itself cast to an integer to determine if you need to append zero to the string that you're generating.
Something along the lines of:
var n = 10.0f;
if(n == (int)n) {
Console.WriteLine("zero");
}