String to decimal and back - c#

I need to take an input from the user, turn all the chars to their decimal value and display the as one string without spaces, then turn it into a string and display it, and afterwards take the number string and turn back to the original string.
A."Hello World" - string
B."72101108108111 87111114108100" - string
C."7210110810811187111114108100" (Processed and displayed) - int
D."72101108108111 87111114108100" - string
E."Hello World" - string
I got to this stage :
string input = Console.ReadLine();
byte[] array = Encoding.ASCII.GetBytes(input);
It's not much but its my first try at creating a program.

here is a example using decimal. but you could also use System.Numerics.BigInteger with its ToString and Parse functions for bigger numbers
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx
using System;
namespace big_number
{
class Program
{
static void Main(string[] args)
{
decimal d = 0;
begining:
try {d = Convert.ToDecimal(Console.ReadLine()); }//<------ HERE IT IS!!!
catch (Exception EX)// look up what exceptions you want to catch
{
Console.WriteLine("try again\r\n\n" + EX.Message);//display error (if you want)
d = 0;//just incase
goto begining; // do not run this code outside of debugger you may get caught in inifinite loop
}
//and back again
string s = "" + d;
Console.WriteLine(s);//we could just pass d
Console.ReadLine();
}
}
}

Related

Splitting large text field c#

EDIT: i have problem which i cant solve. I have large text file. I want select from this file only special data for me.
My code:
class Program
{
static string ticket = "";
static string openTime = "";
static string type = "";
static float size;
static string item = "";
static float price;
static string closeTime = "";
static float priceC;
static float commission;
static float swap;
static float trade;
static void Main(string[] args)
{
ReadFile.ReadAllFile("..\\..\\..\\File.txt");
}
}
public static class ReadFile
{
public static string ReadAllFile(string file)
{
string content = "";
using (StreamReader sr = new StreamReader(file))
{
content = sr.ReadToEnd();
}
Console.WriteLine(content);
return content;
}
}
One line from text file:
18388699 2021.09.03 14:40:14 buy 0.01 eurusd 1.18720 1.16211 1.17961 1.17201 0.00 -0.69 -12.96
In this text there are spaces. I want split this values to my strings.
This code reads the whole text from this text file. But i need select only data to my string from this file. Is there some method or funkcion which can select only important text passages?
Sorry for previous post, i dont want whole script. I am sreaching for some tips and tricks how to do that :D English is not my native language, then i cant describe my problem perfectly, but i tried my best :D
I would probably do something like this:
static void Main()
{
foreach (var line in File.ReadLines(#"..\..\..\File.txt"))
{
var fields = line.Split();
var ticket = fields[0];
var openTime = DateTime.Parse(fields[1] + " " + fields[2], CultureInfo.InvariantCulture);
var price = decimal.Parse(fields[6], CultureInfo.InvariantCulture);
Console.WriteLine($"{ticket}, {openTime}, {price}");
}
}
Read each line of the file using File.ReadLines().
Split on spaces using String.Split().
Index into the fields to get at the data you want.
ticket is just the first field.
For openTime you need to join the second and third field. I also chose to parse to a DateTime.
For things like prices and quantities I would use a decimal data type. In your code you have a float, I would not use that. float's have very low precision, you might get round off error with those. double's are better, but might still have the same problem. The recommended data type for calculations like these is decimal.

ASP.net when i click a button i want to add rows from a grid view to a database but its giving me an error [duplicate]

I'm new with C#, I have some basic knowledge in Java but I can't get this code to run properly.
It's just a basic calculator, but when I run the program VS2008 gives me this error:
I did almost the same program but in java using JSwing and it worked perfectly.
Here's the form of c#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace calculadorac
{
public partial class Form1 : Form
{
int a, b, c;
String resultado;
public Form1()
{
InitializeComponent();
a = Int32.Parse(textBox1.Text);
b = Int32.Parse(textBox2.Text);
}
private void button1_Click(object sender, EventArgs e)
{
add();
result();
}
private void button2_Click(object sender, EventArgs e)
{
substract();
result();
}
private void button3_Click(object sender, EventArgs e)
{
clear();
}
private void add()
{
c = a + b;
resultado = Convert.ToString(c);
}
private void substract()
{
c = a - b;
resultado = Convert.ToString(c);
}
private void result()
{
label1.Text = resultado;
}
private void clear()
{
label1.Text = "";
textBox1.Text = "";
textBox2.Text = "";
}
}
What can be the problem? Is there a way to solve it?
PS: I also tried
a = Convert.ToInt32(textBox1.text);
b = Convert.ToInt32(textBox2.text);
and it didn't work.
The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.
It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.
I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.
I'd declared a string and was formatting it for use with JQTree which requires curly braces ({}). You have to use doubled curly braces for it to be accepted as a properly formatted string:
string measurements = string.empty;
measurements += string.Format(#"
{{label: 'Measurement Name: {0}',
children: [
{{label: 'Measured Value: {1}'}},
{{label: 'Min: {2}'}},
{{label: 'Max: {3}'}},
{{label: 'Measured String: {4}'}},
{{label: 'Expected String: {5}'}},
]
}},",
drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
drv["Min"] == null ? "NULL" : drv["Min"],
drv["Max"] == null ? "NULL" : drv["Max"],
drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);
Hopefully this will help other folks who find this question but aren't parsing numerical data.
If you are not validating explicitly for numbers in the text field, in any case its better to use
int result=0;
if(int.TryParse(textBox1.Text,out result))
Now if the result is success then you can proceed with your calculations.
Problems
There are some possible cases why the error occurs:
Because textBox1.Text contains only number, but the number is too big/too small
Because textBox1.Text contains:
a) non-number (except space in the beginning/end, - in the beginning) and/or
b) thousand separators in the applied culture for your code without specifying NumberStyles.AllowThousands or you specify NumberStyles.AllowThousands but put wrong thousand separator in the culture and/or
c) decimal separator (which should not exist in int parsing)
NOT OK Examples:
Case 1
a = Int32.Parse("5000000000"); //5 billions, too large
b = Int32.Parse("-5000000000"); //-5 billions, too small
//The limit for int (32-bit integer) is only from -2,147,483,648 to 2,147,483,647
Case 2 a)
a = Int32.Parse("a189"); //having a
a = Int32.Parse("1-89"); //having - but not in the beginning
a = Int32.Parse("18 9"); //having space, but not in the beginning or end
Case 2 b)
NumberStyles styles = NumberStyles.AllowThousands;
a = Int32.Parse("1,189"); //not OK, no NumberStyles.AllowThousands
b = Int32.Parse("1,189", styles, new CultureInfo("fr-FR")); //not OK, having NumberStyles.AllowThousands but the culture specified use different thousand separator
Case 2 c)
NumberStyles styles = NumberStyles.AllowDecimalPoint;
a = Int32.Parse("1.189", styles); //wrong, int parse cannot parse decimal point at all!
Seemingly NOT OK, but actually OK Examples:
Case 2 a) OK
a = Int32.Parse("-189"); //having - but in the beginning
b = Int32.Parse(" 189 "); //having space, but in the beginning or end
Case 2 b) OK
NumberStyles styles = NumberStyles.AllowThousands;
a = Int32.Parse("1,189", styles); //ok, having NumberStyles.AllowThousands in the correct culture
b = Int32.Parse("1 189", styles, new CultureInfo("fr-FR")); //ok, having NumberStyles.AllowThousands and correct thousand separator is used for "fr-FR" culture
Solutions
In all cases, please check the value of textBox1.Text with your Visual Studio debugger and make sure that it has purely-acceptable numerical format for int range. Something like this:
1234
Also, you may consider of
using TryParse instead of Parse to ensure that the non-parsed number does not cause you exception problem.
check the result of TryParse and handle it if not true
int val;
bool result = int.TryParse(textbox1.Text, out val);
if (!result)
return; //something has gone wrong
//OK, continue using val
In my case I forgot to put double curly brace to escape. {{myobject}}
You may encounter this exception when you use a string formatter with invalid bracket syntax.
// incorrect
string.Format("str {incorrect}", "replacement")
// correct
string.Format("str {1}", "replacement")
You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.
it was my problem too ..
in my case i changed the PERSIAN number to LATIN number and it worked.
AND also trime your string before converting.
PersianCalendar pc = new PersianCalendar();
char[] seperator ={'/'};
string[] date = txtSaleDate.Text.Split(seperator);
int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());
I had a similar problem that I solved with the following technique:
The exception was thrown at the following line of code (see the text decorated with ** below):
static void Main(string[] args)
{
double number = 0;
string numberStr = string.Format("{0:C2}", 100);
**number = Double.Parse(numberStr);**
Console.WriteLine("The number is {0}", number);
}
After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:
number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number
At that point the Parse(...) method worked as expected.

Attempting to convert a char array to a string and then comparing length

My char[] both consist of exactly one element. My job is to compare the length of the element of the first array to the one of the second.
using System;
using System.Linq;
namespace FirstLecture
{
class Program
{
static void Main(string[] args)
{
char[] ints = {char.Parse(Console.ReadLine())};
char[] ints2 = {char.Parse(Console.ReadLine())};
string s1 = new string(ints);
string s2 = new string(ints2);
if (s1.Length > s2.Length)
{
Console.WriteLine(">");
}
else if (s1.Length < s2.Length)
{
Console.WriteLine("<");
}
else {
Console.WriteLine("=");
}
}
}
}
When I run the program in the console, I get String must be exactly one character long. I'm assuming there is some sort of a data type conversion error, cannot pin point it. Is this the case?
char.Parse only parses one single character, not the entire string you read from Console.ReadLine (so if you just type 'A' in your console, it should work).
Instead, you could just assign the string to the character array:
char[] ints = Console.ReadLine().ToArray();
It seems useless though since you immediate after assigning the characters construct a string out of it again. Both input and resulting strings should be the same.
This should be okay:
string s1 = Console.ReadLine();

Read and return data from text file (C#)

I'm trying to make a program that reads a text file and returns data from it (in this case, currencies). The text file has all currencies listed in this fashion:
USD US Dollars (USA) 1,077600 1,058100 1,097100
JPY Yen (Japan) 133,080000 130,480000 135,680000
... etc.
So when a user inputs a currency code (let's say JPY), the program would print:
JPY Yen (Japan) 133,080000 130,480000 135,680000
And after that, the program would loop and keep asking currencies until the user inputs an empty string.
This is what I have now:
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.IO;
public class Currencies
{
public static void Main()
{
string line;
System.IO.StreamReader currencies = new System.IO.StreamReader("currencies.txt");
Console.Write("Enter currency code >");
string currency = Console.ReadLine();
while ((line = currencies.ReadLine()) != null)
{
if (line.Contains(currency))
{
Console.WriteLine(line);
}
}
Console.ReadLine();
}
}
Now, it returns the correct line, but the loop breaks after the first input, and if you input an empty string, it returns every line of the text file.
Any ideas how to continue making this? Also, should I use ReadAllLines instead of StreamReader?
ReadAllLines vs StreamReader
If you text file is really big, than scanning the file row by row is a good practice. In any other case to ReadAllLines will be a better choice, especially when scanning several times.
Empty string returns results
You're using the Contains method, which in turns search inside the string an empty string. Every string has inside of her an Empty string.
Solution: Test to see whatever the user entered an empty string and handle it the way you see fit.
Input only once
You're only searching for the input once, than it can't guess you want it to rescan again.
Solution: Make another loop, which will wrap the current loop until you need it to stop.
this should solve it in the most effective way:
public static void Main()
{
string line;
bool IsEmptyString = false;
List<string> lines = new List<string>();
using (System.IO.StreamReader currencies = new System.IO.StreamReader("currencies.txt")
{
while ((line = currencies.ReadLine()) != null)
{
lines.Add(line);
}
}
while (!IsEmptyString)
{
string tempLine = "";
Console.Write("Enter currency code >");
string currency = Console.ReadLine();
IsEmptyString = currency == "" ? true : false;
tempLine = lines.FirstOrDefault(x => x.Contains(currency));
if (tempLine!="")
{
Console.WriteLine(tempLine);
}
tempLine = "";
}
}
You can use the following code. Explanations inline
public static void Main()
{
//read all lines from file only once, and keep for future use
var currencyDetails = File.ReadAllLines(#"C:\YourDirectory\currencies.txt");
string input = string.Empty;
while (true) //keep looping until empty input by user
{
Console.Write("Enter currency code > ");
input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input)) //stop loop
break;
//from all lines of file, get the line where line starts with the user input e.g. usd
var currencyDetail = currencyDetails.FirstOrDefault(l => l.StartsWith(input.ToUpper()));
if (currencyDetail != null) //if a matching currency is found, show it
{
Console.WriteLine(currencyDetail);
}
}
Console.ReadLine();
}

How to get rid of conversion overheads?

Take this example:
customer.Salary = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
(1) Why in C# we need to always put .ToString() to get it right?
(2) Convert.To... Doesn't it creates overheads unnecessarily?
Further in the below given code: It gives error: "Input string was not in a correct format", after accepting user input.
// Main begins program execution.
public static void Main()
{
Customer customer = new Customer();
// Write to console/get input
Console.Write("Enter customer's salary: ");
customer.Salary = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
Console.WriteLine("Salary in class variable is: {0}", customer.Salary.ToString());
Console.Read();
}
class Customer
{
public Decimal Salary { get; set; }
}
Here again, either I must use:
string sal = Convert.ToDecimal(string.Format("{0}! ", Console.ReadLine().ToString()));
customer.Salary = Convert.ToDecimal(sal);
Or, I must change the data type itself in the Customer class.
Can this overhead be avoided with anything in Generics?
You do not need to call .ToString().
Yes, it does.
You're trying to write
customer.Salary = Decimal.Parse(Console.ReadLine());
Your current code does the following:
Console.ReadLine(): Reads a line from the console, returning a String object.
(...).ToString() Returns the same String object
string.Format("{0}! ", (...)): Returns a new String object containing the original string followed by !.
Convert.ToDecimal((...)): Tries to parse that into a Decimal value.
Since the string ends with !, it fails
I think you'll be happier if you use Decimal.Parse or Decimal.TryParse to do the conversions, rather than relying on Convert.ToDecimal. You can write:
Decimal tempSal;
string sal = Console.ReadLine();
if (Decimal.TryParse(sal, out tempSal))
{
customer.Salary = tempSal;
}
else
{
// user entered bad data
}

Categories

Resources