TextBox string with variables - c#

I need to be able to make a textbox string take from variables and put the variables into a string.
textBoxEmailTemplateUT.Text = "The documents are as follows: FileNameHere ► {TotalPanelCountUtah} ► {TotalkWUtah} ► ElectricalUsageOffsetHere InformationAboutTheSystemHere If There are any questions or concerns, please reply to this email. Regards YourNameHere");
This is suppose to be a type of email template after someone does a few calculations in the other code (not displayed). The {TotalPanelCountUtah} and {TotalkWUtah} are both double variables that I need to be put into the string in the textbox. Some assistance would be appreciated.

Using C# 6, you can use string interpolation, as such:
string txt = $"The values are: {value1}, {value2}";
The syntax requires that you put a $ before the string and enclose any variables within braces ({}).
Without string interpolation (pre-c#6), you can use:
string txt = String.Format("The values are: {0}, {1}", value1, value2);
This snippet of code does the same as the first one. String.Format will format a string, replacing each of the values between braces with its corresponding argument.
If:
double value1 = 0.5;
double value2 = 1.5;
then, for both of the snippets (interpolation and string.Format):
txt == "The values are: 0.5, 1.5"`

as Clay mentioned in comment use string.Format
textBoxEmailTemplateUT.Text = string.Format("The documents are as follows: FileNameHere ► {0} ► {1} ► ElectricalUsageOffsetHere InformationAboutTheSystemHere If There are any questions or concerns, please reply to this email. Regards YourNameHere",TotalPanelCountUtah, TotalkWUtah);
where TotalPanelCountUtah TotalPanelCountUtah are double type

string.Format is generally preferred, but I included a second approach using string.replace below. It is probably also a good idea to round the values before displaying them.
double val1 = 1.2345;
double val2 = 8.7654;
// recommended
textBox1.Text = string.Format(
"Value one is {0:0.00}, and value two is {1:0.00}.",
val1, val2);
// also an option
textBox1.Text = "Value one is val1, and value two is val2."
.Replace("val1", Math.Round(val1, 2).ToString())
.Replace("val2", Math.Round(val2, 2).ToString());

Related

Read out one Line for two variables but one is double and the other one is a string

I wanted to read out two variables from one line, so I used var.
I encountered some difficulties with the second variable beeing a double and the first one beeing a string.
var inputParts = Console.ReadLine().Split(' ');
temp0 = inputParts[0];
temp1 = Convert.ToDouble(inputParts[1]);
What's wrong with this type of code? Visual Studio didn't help me out there.
Thank you in forward :)
temp1 = double.Parse(inputParts[1]);
I guess that temp0 and temp1 do not have the right type. For that code to work they should be defined as:
string temp0;
double temp1;
Edit: based on your comment below what you're actually getting is a run time exception because the string you're trying to parse does not match the expected format of a double.
You could print inputParts[1] to check what it actually contains.
If you're expecting your double to look like 1.0 (with a . for decimal separator) then you should do
temp1 = float.Parse(inputParts[1],CultureInfo.InvariantCulture);
If you don't use CultureInfo.InvariantCulture then the way that the double is parsed will depend on the user's locale. The locale might be such that it expects a comma to be the decimal separator e.g. "1,0" so when it sees a '.' it will throw an exception.
Note that you will need to add
using System.Globalization;
Here is a complete program that works:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string temp0;
double temp1;
var inputParts = Console.ReadLine().Split(' ');
temp0 = inputParts[0];
temp1 = double.Parse(inputParts[1], CultureInfo.InvariantCulture);
Console.WriteLine(string.Format("The double was parsed as {0}", temp1));
}
}
If you run this and enter input like
firstPartThatIsIgnored 100.5
You will get output
The double was parsed as 100.5
What language are you using? Presuming you're splitting based on a Space, I'd parse it as a String array. Check and see the type of the part first, before trying to convert to avoid exceptions.
string input = "x 3.3 z 2";
string[] cars = input.split(" ");
double x = double.TryParse(cars[1]);
If you are trying to just extract a double from a random string of input, you could use something like this:
string inputData = "sfdsdf2.2222sfdsfs";
var data = Regex.Match(inputData, "^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$").Value;

How to convert currency format label to double for calculation purpose

I have a label (lblAmountTendered) which contains Currency String in it. I would like to convert it into double to perform some calculation. However, it shown an Error Message: Input string was not in a correct format in the first statement.
Here is my code:
double balance = double.Parse(amount) - double.Parse(lblAmountTendered.Text.ToString());
lblBalanceDue.Text = balance.ToString("c2",CultureInfo.CreateSpecificCulture("en-MY"));
For Example:
lblAmountTendered = RM 15
I want to retrieve the value of it (15) for calculation.
Looking forward for the solution. I appreciate for your help! :)
PROBLEM SOLVED
lblAmountTendered.Text.ToString().Remove(0,3)
Remove(0,3) helps us to remove 'RM' from 'RM 15', so we can convert it to double or float easily as shown in below:
float.Parse(lblAmountTendered.Text.ToString().Remove(0, 3))
Here you first need to retrieve the numeric value from a string using below regex:
string resultNum = Regex.Match(lblAmountTendered.Text, #"\d+").Value;
and then use resultNum in your code like-
double balance = double.Parse(amount.ToString()) - double.Parse(resultNum);
lblBalanceDue.Text = balance.ToString("c2",CultureInfo.CreateSpecificCulture("en-MY"));

C# Get exact string formation from 'double' type

As I'm working on C#, I have one field named 'Amount'.
double amount = 10.0;
So, I want the result like '10.0' after converting it to string.
If my value
amount = 10.00, then I want result '10.00' after converting it to string.
So, Basically I want exact result in string as it is in double type. (With precisions).
Thanks in advance.
string result = string.Format( "{0:f2}", amount );
What you ask is not possible. A double in C# is a simple 64-bit floating-point value. It doesn't store precision. You can print your value with one decimal places, or two, as other answers describe, but not in a way that's "preserves" the variable's original precision.
string amountString = amount.ToString("N2");
"N2" is the format string used as the first parameter to the .ToString() method.
"N" stands for number, and 2 stands for the number of decimal places.
More on string format's here:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
As #Michael Petratta points out, double doesn't carry with it the precision of the input. If you need that information, you will need to store it yourself. Then you could reconstuct the input string doing something like:
static public string GetPrecisionString( double doubleValue, int precision)
{
string FormattingString = "{0:f" + precision + "}";
return string.Format( FormattingString, doubleValue);
}

Formatting my string

How can I format a string like this:
string X = "'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}'",????
I remember I used to be able to put a comma at the end and specify the actual data to assign to {0},{1}, etc.
Any help?
Use string.Format method such as in:
string X = string.Format("'{0}','{1}','{2}'", foo, bar, baz);
An alternative is to use Join, if you have the values in a string array:
string x = "'" + String.Join("','", valueArray) + "'";
(Just wanted to be different from the 89724362 users who will show you how to use String.Format... ;)
String.Format("'{0}', '{1}'", arg0, arg1);
The String.Format method accepts a format string followed by one to many variables that are to be formatted. The format string consists of placeholders, which are essentially locations to place the value of the variables you pass into the function.
Console.WriteLine(String.Format("{0}, {1}, {2}", var1, var2, var3));
Your question is a bit vague, but do you mean:
// declare and set variables val1 and val2 up here somewhere
string X = string.Format("'{0}','{1}'", val1, val2);
Or are you asking for something else?
use string.format, and put individual format specifiers inside the braces, after the number and a colon, as in
string s = string.Format(
" {0:d MMM yyyy} --- {1:000} --- {2:#,##0.0} -- {3:f}",
DateTime.Now, 1, 12345.678, 3e-6);
and, as you can see from the example, you don;t need the single quotes to delineate literals, anything not inside braces will be output literally
are you looking for:
String.Format("String with data {0}, {1} I wish to format", "Foo", "Bar");
would result in
"String with data Foo, Bar I wish to format"
Use string.Format as in
var output = string.Format("'{0}', '{1}'", x, y);

String has how many parameters

Before using String.Format to format a string in C#, I would like to know how many parameters does that string accept?
For eg. if the string was "{0} is not the same as {1}", I would like to know that this string accepts two parameters
For eg. if the string was "{0} is not the same as {1} and {2}", the string accepts 3 parameters
How can I find this efficiently?
String.Format receives a string argument with format value, and an params object[] array, which can deal with an arbitrary large value items.
For every object value, it's .ToString() method will be called to resolve that format pattern
EDIT: Seems I misread your question. If you want to know how many arguments are required to your format, you can discover that by using a regular expression:
string pattern = "{0} {1:00} {{2}}, Failure: {0}{{{1}}}, Failure: {0} ({0})";
int count = Regex.Matches(Regex.Replace(pattern,
#"(\{{2}|\}{2})", ""), // removes escaped curly brackets
#"\{\d+(?:\:?[^}]*)\}").Count; // returns 6
As Benjamin noted in comments, maybe you do need to know number of different references. If you don't using Linq, here you go:
int count = Regex.Matches(Regex.Replace(pattern,
#"(\{{2}|\}{2})", ""), // removes escaped curly brackets
#"\{(\d+)(?:\:?[^}]*)\}").OfType<Match>()
.SelectMany(match => match.Groups.OfType<Group>().Skip(1))
.Select(index => Int32.Parse(index.Value))
.Max() + 1; // returns 2
This also address #280Z28 last problem spotted.
Edit by 280Z28: This will not validate the input, but for any valid input will give the correct answer:
int count2 =
Regex.Matches(
pattern.Replace("{{", string.Empty),
#"\{(\d+)")
.OfType<Match>()
.Select(match => int.Parse(match.Groups[1].Value))
.Union(Enumerable.Repeat(-1, 1))
.Max() + 1;
You'll have to parse through the string and find the highest integer value between the {}'s...then add one.
...or count the number of sets of {}'s.
Either way, it's ugly. I'd be interested to know why you need to be able to figure out this number programatically.
EDIT
As 280Z28 mentioned, you'll have to account for the various idiosyncrasies of what can be included between the {}'s (multiple {}'s, formatting strings, etc.).
I rely on ReSharper to analyze that for me, and it is a pity that Visual Studio does not ship with such a neat feature.

Categories