functions along a variable on c# - c#

I am new into programming with c# and I am trying to do a Console.WriteLine where I have $ and a variable inside {}, instead of the usual way that is done in c#.
However when I try to add a fuction it does'nt work, because I don't know the correct syntax to do it.
example (function Math.round)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
decimal Euro, Dolar;
decimal tax = 1.19590m;
Console.WriteLine("Convert euro into dólar- day 06/05/2018.\nWhat is the amount in euros? ");
Euro = decimal.Parse(Console.ReadLine());
Dolar = Euro * tax;
Console.WriteLine($"The final value is: (Math.Round,2){Dolar} dólars");
Console.ReadKey();
}
}
}

I'm not sure where did you read about that syntax... but that should be something like:
$"The final value is: {Math.Round(Dolar, 2)} dólars"
The parentheses inside the string literal have no special meaning... all the parsed code must be within the brackets for interpolated strings. Think of it as:
"The final value is: " + Math.Round(Dolar, 2).ToString() + " dólars"
Or
var final = Math.Round(Dolar, 2);
$"The final value is: {final} dólars"
If you are working with an IDE (Visual Studio, VSCode, etc.) which is coloring the syntax, it should be obvious there (everything inside the brackets is colored as regular code, not as the string)
Also, you don't really need Math.Round here, but that wouldn't answer your question :-)

Try this:
Console.WriteLine("The final value is: {0} dólars", Math.Round(Dolar, 2));

Related

C# Wrong Value stored in variable

I am fairly new to programming so have some mercy ;)
I am trying to build a program that can solve equations and give gradient and so on in c#, so I can make it more complex gradually. Problem is, there appears to be a wrong value from my input when I tried to start building it.
Console: Given value for "a":
9 The Output: 57
My Code:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input an linear Eqasion in the following Pattern -- a * x + b");
Console.Write("Given value for \"a\":");
decimal aValue;
aValue = Console.Read();
Console.Write(aValue);
}
}
}
Console.Read() returns an int, but not in the way you think. It returns the numeric value of the typed character, not the human-intuitive interpretation of a character that coincidentally happens to be a number. Consider for example what it would return if you type a letter, or any other non-numeric character.
And what is the numeric (decimal) value for the character '9'? 57 is.
It sounds like you want to read the line, not the character. For example:
string aValue;
aValue = Console.ReadLine();
Console.Write(aValue);
Remember that you'll need to press return to send the line to the application.
If you'll later need the value to be numeric, you'll still want to input the string but will want to parse it. For example:
string aValue;
aValue = Console.ReadLine();
if (decimal.TryParse(aValue, out decimal numericValue)
{
Console.Write(numericValue);
}
else
{
// The value could not be parsed as a decimal, handle this case as needed
}
Console.Read returns the character code entered on the command line in this scenario. The ASCII character code of 9 is 57. If you're wanting numeric input, you'd be better using Console.ReadLine with Decimal.Parse (or better yet, Decimal.TryParse)
It is also worth noting that Console.Read only returns one character at a time, meaning for any inputs past 1 digit you'll need special handling. I highly recommend using ReadLine and parsing the string over handling converting the character codes to the number they represent.

Title case capitalising letter after ‘

Is there a .net bug causing the following code to capitalise the S, giving "Ben’S Pies"?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Globalization;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
string value = "ben’s pies";
string titleCase = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);
Console.WriteLine(titleCase);
}
}
}
You can see the output at: https://rextester.com/ (where I tried it).
If you print a dump of the value:
string value = "ben’s pies";
Console.Write(string.Join(" ", value.Select(c => ((int)c).ToString("x4"))));
You'll get
0062 0065 006e 2019 0073 0020 0070 0069 0065 0073
Now, let's have a look for Unicode U+2019
https://www.fileformat.info/info/unicode/char/2019/index.htm
And we see that ’ is not an apostroph, but "RIGHT SINGLE QUOTATION MARK (U+2019)." That's why ToTitleCase does work right (it capitalizes the word after a punctuation - a quotation mark). To amend your example put apostroph instead of quotation:
string value = "ben's pies";
// Ben's Pies
string titleCase = CultureInfo.GetCultureInfo("en-US").TextInfo.ToTitleCase(value);
ToTitleCase does indeed seem to treat the right single quotation mark as a separator between the words it converts to title case. The documentation says:
the ToTitleCase method provides an arbitrary casing behavior which is not necessarily linguistically correct. A linguistically correct solution would require additional rules, and the current algorithm is somewhat simpler and faster. We reserve the right to make this API slower in the future.

Using PromptforLetter and DisplayLetter in C#

Below is a homeowrk assignment I've been working on.
I need to create a class called FormattedOutput in a file called FormattedOutput.cs. That class will have the following methods:
char PromptforLetter(void) - this method will return a value
void DisplayLetter(char letter) - this method will accept a value to display
Main should be in a file named mainModule.cs
Main will PromptforLetter for each character in your name and store each character into a char data type.
Then DisplayLetter(letter1) should display each letter as:
the actual letter
the decimal value of the key
the hexadecimal value of the key
the octal value of the key
the binary value of the key
Information should be displayed first...
Then prompts for each letter of your name.
Then a Table showing each value
Char Decimal Hex Octal Binary
Here is the horrible mess I have at this time
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class formattedOutput
{
char PromptforLetter(string prompt)
{
string value;
char achar;
Console.WriteLine("A", prompt);
Console.WriteLine("L", prompt);
Console.WriteLine("M", prompt);
Console.WriteLine("A", prompt);
Console.Read();
value = Console.ReadLine();
achar=Convert.ToChar(value.Substring(0,1));
return achar;
}
void DisplayLetter (char letter)
{
Console.WriteLine("A");
Console.Read();
I'm fairly uncertain of what you're going for, and it might help to clear up your introduction to the problem (or instance, we don't need to know filenames and such, just give the relevant details). It also seems like you're asking quite a few questions, so I'm going to focus on what I think you actually mean to ask.
The impression I'm getting is that you are to write a console application in C#, with a method to read a single character from user-input, then another one to echo it back to them using several number formats.
If that is, in fact, the case, you probably want something like this:
public char PromptforLetter(string prompt)
{
Console.Write(prompt + " "); // This prints out the prompt with a space, and no
// following line break
// Now you have a choice. Should you take the first key that is pressed, or
// should the user have to press enter?
// Option 1:
char ret = Console.ReadKey().KeyChar;
Console.WriteLine(); // Not necessary, but it improves user experience
return ret;
// Option 2:
return Console.ReadLine()[0]; // take the first indexed character from the
// string entered by the user. Strings have
// integer-indexers, so you can access single them
// characters in kind of like you would if they were
// a string array.
}
Printing the character is a bit simpler:
public void DisplayLetter(char val)
{
Console.Write("Char: {0}", val);
Console.Write("Decimal: {0}", (int)val);
Console.Write("Hex: {0:X}", (int)val);
Console.Write("Octal: {0}", Convert.ToString((int)val, 8));
Console.Write("Binary: {0}", Convert.ToString((int)val, 2));
}
Beyond that, it's mostly just up to you and what the instructor is looking for, specifically.

C# Converting a Currency String to Double

I have a basic understanding of C# and the .NET Framework, I have been given an assignment to build a POS (Point Of Sales) screen, I have currently hit a small brick wall trying to convert a currency related string back to a double.
I have two list boxes and several product buttons on the screen, the buttons are populated using a library class provided to us (essentially showing we can work with components)
One list box holds the product name while the other holds the price of that product, when a product button is selected it takes the product name from the buttons text and within its tag there is the price which is added to the list box of prices.
my problem is I want to show the prices in the List Box as a currency also that it shows all '0' I can do this no problem by doing either the following
value.ToString("C");
string.Format("{0:C}",value);
or using Convert etc.
Although because I have done this if I want to remove an item from the list by double clicking I need to take away the price from the total so I need to convert to back to double although because its in its current format I get an error when trying to perform that action I have looked around and I cannot seem to find anyway around it, the only option I can see is just leaving the string value as it is and not convert it to a currency format.
the ERROR: {"Input string was not in a correct format."}
Code Snippet
private void panelBtns_Click(object sender, EventArgs e)
{
Button panelBtn = (Button)sender;
lstProduct.Items.Add(panelBtn.Text);
double price = Convert.ToDouble(panelBtn.Tag);
>>CURRENCY FORMAT>> lstPrice.Items.Add(string.Format("{0:C}",price));
dblTotal = dblTotal + Convert.ToDouble(panelBtn.Tag);
lblTotal.Text = string.Format("{0:C}", dblTotal);
lblOutput.Text = "0";
lblOutput.Tag = "0";
}//End Panel Buttons
private void lstProduct_DoubleClick(object sender, EventArgs e)
{
int index = lstProduct.SelectedIndex;
lstPrice.SelectedIndex = lstProduct.SelectedIndex ;
>> ERROR HERE >> double price = Convert.ToDouble(lstPrice.GetItemText(lstPrice.SelectedItem));
dblTotal = dblTotal - price;
lstProduct.Items.RemoveAt(index);
lstPrice.Items.RemoveAt(index);
lblTotal.Text = string.Format("{0:C}", dblTotal);
}
Would anyone have any idea how I could possibly fix this, I had though about creating an invisible list to store the actual value of the tag so I can use that for later but would there be any other methods?
NOTE: I am also aware that using double for currency is not a very reliable
The easiest way to parse the C format is probably with
Double.Parse(text, System.Globalization.NumberStyles.Currency)
Of course you would always want to use Decimal to handle currency, and Decimal.Parse takes the same parameters.
In this case, though, you would want to store your internal numeric values along with their textual representation rather than converting to a string and then parsing back into a number.
other way, but please note, that you must try all cultures if removing symbol gives just decimal string, use Gabe's answer (posted just before mine :D)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Threading;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
//US-en culture / default I'm developing on
string currencyString = "$12.99"; //assuming got from: lstPrice.GetItemText(lstPrice.SelectedItem);
CultureInfo ci = Thread.CurrentThread.CurrentUICulture;
double d = Convert.ToDouble(currencyString.Replace(ci.NumberFormat.CurrencySymbol, ""));
//using custom culture
currencyString = "12.99zł";
ci = CultureInfo.GetCultureInfo("PL-pl");
d = Convert.ToDouble(currencyString.Replace(ci.NumberFormat.CurrencySymbol, ""));
}
}
}
You may want to look at assigning the decimal too with Math.Round Method
https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx

How can I use C# contains method with the functionality of sql LIKE condition?

I want to be able to use the contains function the same way the like operator works in sql. So when I call .contains(%This%%%%%%is%%my%string%%) from a list or whatever such as "This is my string " then the function will return true. I've done a lot of searching and it seems like a lot of people would like this function. So how can this be done or how can a custom like function with the same functionality be made?
EDIT
Thank you, for the quick response. I was able to use a regular expressions inside of my own custom Like function. Below is the code for anyone else who wants to use something similar to SQL Like. In this code the user would input the databaze value and then spaces in that value are replaced with .* to ignore anything in-between the values.Just like using the % to replace spaces and values in SQL. I can then use .Like on my string value called testValue that I am searching through to return true or false depending on if the words or whatever are in my string. I also added ToUpper to ignore the case.
//C# Like function
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace sqllinqstuff
{
class Program
{
static void Main(string[] args)
{
string testValue = "Big RED Car";
string databaze = "big red CAR";
string databaze3 = databaze.Replace(" ", ".*");
databaze3 = databaze3.Replace(" ", ".*");
Console.WriteLine(databaze3);
Console.WriteLine(testValue.Like(databaze3));
Console.Read();
}
}
public static class CaseyStringExtension
{
public static bool Like(this string str,string value)
{
if (!string.IsNullOrEmpty(str))
{
Regex r = new Regex(value.ToUpper());
if (r.IsMatch(str.ToUpper()))
return true;
}
return false;
}
}
}
The result of this test will be true.
The way this would be done is with Regex. The syntax is not the same as a SQL LIKE query so there will be a bit of a learning curve. This is a good tutorial site I often reference, it can get you started with the basics.
Translating your original string you asked about, the regex search pattern would be
.*This.*is.*my.*string.*
Once you get good at it you can do searches like this one I helped create for a password complexity checker
(?=^.{8,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])(?=^.*[^\s].*$).*$
The above search looks for a string that has at least 8 characters with at least one lower case letter, one upper case letter, one special character, and no white-space characters.

Categories