static void Main(string[] args)
{
//read in the file
StreamReader convert = new StreamReader("../../convert.txt");
//define variables
string line = convert.ReadLine();
int conversion;
int numberIn;
float conversionFactor;
Console.WriteLine("Enter the conversion in the form (amount,from,to)");
String inputMeasurement = Console.ReadLine();
string[] inputMeasurementArray = inputMeasurement.Split(',');
while (line != null)
{
string[] fileMeasurementArray = line.Split(',');
if (fileMeasurementArray[0] == inputMeasurementArray[1])
{
if (fileMeasurementArray[1] == inputMeasurementArray[2])
{
Console.WriteLine("{0}", fileMeasurementArray[2]);
}
}
line = convert.ReadLine();
//convert to int
numberIn = Convert.ToInt32(inputMeasurementArray[0]);
conversionFactor = Convert.ToInt32(fileMeasurementArray[2]);
conversion = (numberIn * conversionFactor);
}
Console.ReadKey();
}
On the line conversionFactor = Convert.ToInt32(fileMeasurementArray[2]);, I am getting an error saying "Input string was not in correct format". Please help!
The text file consists of the following:
ounce,gram,28.0
pound,ounce,16.0
pound,kilogram,0.454
pint,litre,0.568
inch,centimetre,2.5
mile,inch,63360.0
You are trying to convert a float to an int.
Define conversionFactor as a double
also the variable conversion needs to be a double aswell.
like so
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace measurementConverter {
class Program
{
static void Main(string[] args)
{ //read in the file
StreamReader convert = new StreamReader("../../convert.txt");
//define variables
string line = convert.ReadLine();
double conversion;
int numberIn;
double conversionFactor;
Console.WriteLine("Enter the conversion in the form (amount,from,to)");
String inputMeasurement = Console.ReadLine();
string[] inputMeasurementArray = inputMeasurement.Split(',');
while (line != null)
{
string[] fileMeasurementArray = line.Split(',');
if (fileMeasurementArray[0] == inputMeasurementArray[1])
{
if (fileMeasurementArray[1] == inputMeasurementArray[2])
{
Console.WriteLine("{0}", fileMeasurementArray[2]);
}
}
line = convert.ReadLine();
//convert to int
numberIn = Convert.ToInt32(inputMeasurementArray[0]);
conversionFactor = Convert.ToDouble(fileMeasurementArray[2]);
conversion = (numberIn * conversionFactor);
}
Console.ReadKey();
}
}
}
According to the line of the text file, fileMeasurementArray[2] will be 28.0 pound. This cannot be converted to an int. You should remove the string and keep only the number 28.0.
UPDATE: the question was updated and the line of text file corrected. So my previous answer does'nt make sense anymore.
The problem occurs probably because you are trying to convert a float to an int.
'28.0 pound' isn't an integer. I'd imagine that's where your problem lies.
numberIn and conversionFactor are floats, not Ints. Use:
float numberIn;
float conversionFactor;
...
//convert to float
numberIn = Convert.ToSingle(inputMeasurementArray[0]);
conversionFactor = Convert.ToSingle(fileMeasurementArray[2]);
Related
I have a large float that I want to convert into a string with commas without rounding.
Here is what I have:
String.Format("{0:#,###}", val);
This turns 17154177 into 17,154,180
I would like to keep the commas but not round at the end using c#.
This may be what you're looking for
using System;
class MainClass {
public static void Main (string[] args) {
float original = 17154177;
// 1. Convert the number to a string
string value = original.ToString("R");
// 2. Reverse the string
string reversed = Reverse(value);
// 3. Add the comma on each third number, backwards
string formatted = "";
for(int i = 0; i < reversed.Length; i++) {
if ((i+1) % 3 == 0) {
formatted += reversed[i] + ",";
} else {
formatted += reversed[i];
}
}
// 4. Reverse it back to the original order
formatted = Reverse(formatted);
Console.WriteLine (formatted);
}
/* Reverses a string */
public static string Reverse(string text)
{
char[] cArray = text.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverse += cArray[i];
}
return reverse;
}
}
I got the reverse method from this question.
Change your data type to decimal (28-29 significant digits) to have higher precision compared to float (7 digits).
Or you can change it to var. It will let the compiler figure out the best data type to use.
var number = 17154177;
Console.WriteLine(String.Format("{0:#,###}", number));
See this fiddler link, working code
My front-end application sends strings that look like this:
"12-15"
to a back-end C# application.
Can someone give me some pointers as to how I could extract the two numbers into two variables. Note the format is always the same with two numbers and a hyphen between them.
string stringToSplit = "12-15";
string[] splitStringArray;
splitStringArray = stringToSplit.Split('-');
splitStringArray[0] will be 12
splitStringArray[1] will be 15
Split the string into parts:
string s = "12-15";
string[] num = s.Split('-');
int part1 = Convert.ToInt32(num[0]);
int part2 = Convert.ToInt32(num[1]);
int[] numbers = "12-15".Split('-')
.Select(x => {
int n;
int.TryParse(x, out n);
return n;
})
.ToArray();
We call Split on a string instance. This program splits on a single character
string s ="12-15";
string[] words = s.Split('-');
foreach (string word in words)
{
int convertedvalue = Convert.ToInt32(word );
Console.WriteLine(word);
}
string[] ss= s.Split('-');
int x = Convert.ToInt32(ss[0]);
int y = Convert.ToInt32(ss[1]);
more info
You can use the below code to split and it will return string for each value, then you can typecast it to any type you wish to ...
string myString = "12-15-18-20-25-60";
string[] splittedStrings = myString.Split('-');
foreach (var splittedString in splittedStrings)
{
Console.WriteLine(splittedString + "\n");
}
Console.ReadLine();
Here is the correct version without the wrong code
string textReceived = "12-15";
string[] numbers = textReceived.Split('-');
List<int> numberCollection = new List<int>();
foreach (var item in numbers)
{
numberCollection.Add(Convert.ToInt32(item));
}
String numberString = "12-15" ;
string[] arr = numberString.Split("-");
Now you will get a string array , you can use parsing to get the numbers alone
int firstNumber = Convert.ToInt32(arr[0]);
Helpful answer related to parsing :
https://stackoverflow.com/a/199484/5395773
You could convert that string explicitly to an integer array using Array.ConvertAll method and access the numbers using their index, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = Array.ConvertAll(number.Split('-'), int.Parse);
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[1]);
}
}
}
Or you can explicitly convert the numeric string using int.Parse method, the int keyword is an alias name for System.Int32 and it is preffered over the complete system type name System.Int32, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = number.Split('-');
var one = int.Parse(numbers[0]);
var two = int.Parse(numbers[1]);
Console.WriteLine(one);
Console.WriteLine(two);
}
}
}
Additional read: Please check int.Parse vs. Convert.Int32 vs. int.TryParse for more insight on parsing the input to integer
string str = null;
string[] strArr = null;
int count = 0;
str = "12-15";
char[] splitchar = { '-' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
MessageBox.Show(strArr[count]);
}
I've been creating a code breaking software and I need to convert the characters from a text file into ascii numbers to allow the shift. I have left my code below but could someone explain how I could do this?
using System;
using System.IO;
namespace CipherDecoder
{
class Program
{
static void Main(string[] args)
{
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
string cipherText = File.ReadAllText(fileText);
string output = #"C:\\Users\Samuel\Documents\Computer_Science\PaDS\output.txt\";
char[] cipherChars = new char[691];
int j = 0;
foreach (char s in cipherText)
{
cipherChars[j] = s;
j++;
}
for(int i = 0; i < cipherChars.Length; i++)
{
cipherChars[i] = cipherChars[i];
}
}
}
}
To get the int values into an int array you could just do this with as a LINQ select. For example:
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
int [] charactersAsInts = File.ReadAllText(fileText).Select(chr => (int)chr).ToArray();
You can,
var asciiNumbersArray = cipherText.Cast<int>().ToArray();
If you cast a char to int you get the ascii number in decimal system.
I have a string such as 45,5235234096284 or 112,013574120648. I want to convert it to double. I have tried following code but i got error 'System.Globalization.CultureInfo' does not contain a definition for 'GetCultureInfo
' because of framework version. I'm not able to change framework option.I have looked some another solution but i couldn't understand clearly.What is the best way converting these string to double with their commas.
var convertedMapPoint = double.Parse(mapPoint, CultureInfo.GetCultureInfo(1053));
First, you should split your input on spaces, since that is the separator:
string input = "45,5235234096284 112,013574120648";
string[] splitted = input.Split(' ');
Then you can iterate over the result of the splitting, and convert each to a double:
List<double> doubles = new List<double>();
foreach (string s in splitted)
{
doubles.Add(double.Parse(s, new CultureInfo("fr-FR")));
}
I used fr-fr, since it has a comma as decimal separator, but you can use any culture that does that.
If that doesn't work for you, and you are 100% sure there is no . as thousand separator, you can use this:
doubles.Add(double.Parse(s.Replace(",", ".")));
Then you might want to add the invariant culture to be platform independent:
doubles.Add(double.Parse(s.Replace(",", ".", CultureInfo.InvariantCulture)));
You should split the string into array delimited by Space, and than convert each part.
string mapPoint = "45,5235234096284 112,013574120648";
var mapPoints = mapPoint.Split(' ');
var convertedMapPointX = double.Parse(mapPoints[0], CultureInfo.GetCultureInfo(1053));
var convertedMapPointY = double.Parse(mapPoints[1], CultureInfo.GetCultureInfo(1053));
Console.WriteLine("X: {0}\tY: {1}", convertedMapPointX, convertedMapPointY);
Output:
X: 45.5235234096284 Y: 112.013574120648
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringToMapPoint
{
class Program
{
static void Main(string[] args)
{
string mapPointStr = "45,5235234096284 112,013574120648";
MapPoint mp = mapPointStr.ToMapPoint();
Console.WriteLine(mp.ToString());
}
}
public class MapPoint
{
public double X { get; set; }
public double Y { get; set; }
public override string ToString()
{
return "X: " + X + " Y: " + Y;
}
}
public static class MapPointHelper
{
public static MapPoint ToMapPoint(this string str)
{
var split = str.Replace(".", ",").Split(' ');
return new MapPoint() { X = Double.Parse(split[0]), Y = Double.Parse(split[1]) };
}
}
}
When trying to cast an int from an array string value in the following code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace hourscount
{
class Program
{
static void Main(string[] args)
{
string delimiter = ":";
string time1 = Console.ReadLine();
string time2 = Console.ReadLine();
if (time1 == null || time2 == null)
{
Console.WriteLine("Program expects two values!");
Console.ReadLine();
}
else
{
string[] time1var = time1.Split(new string[] {delimiter}, StringSplitOptions.None);
string[] time2var = time2.Split(new string[] { delimiter }, StringSplitOptions.None);
int time2Intvar1 = int.TryParse(time2var[0]);
int time1Intvar1 = int.TryParse(time1var[0]);
int time2Intvar2 = int.TryParse(time2var[1]);
int time1Intvar2 = int.TryParse(time1var[1]);
int realHours = (time2Intvar1 - time1Intvar1);
Console.ReadLine();
}
}
}
}
I am getting the following error; Error 1 No overload for method 'TryParse' takes 1 argument
Use it as
int time2Intvar1;
bool isOK = int.TryParse(time2var[0],out time2Intvar1);
For more information see
http://www.dotnetperls.com/int-tryparse
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
You need to provide the out parameter for int.TryParse:
int time2Intvar1;
bool canBeParsed = int.TryParse(time2var[0], out time2Intvar1);
It is initalized afterwards.