Converting String to Double from ListBox to TextBox - c#

// Calculating and diplaying pricing in list.
for (double MAX = 4.25; MAX >= MIN; MAX -= 0.05)
{
Price = (X * MAX);
prices = Price.ToString("c");
listFinances.Items.Add(prices);
}
---
private void listFinances_SelectedIndexChanged(object sender, EventArgs e)
{
string TotalPrice = listFinances.SelectedItem.ToString();
double stateIncentive = (Convert.ToDouble(TotalPrice) / 4);
txtStateTax.Text = stateIncentive.ToString();
}
So I'm trying to take a ListBox of string currency values, turn them into a double, divide them by 4, and display the result in a TextBox. The user will select the ListBox value and the program should automatically divide by 4 and display.
It's not working however. The program always does an exception throw when you click the ListBox item. The exception is thrown at:
double stateIncentive = (Convert.ToDouble(TPrice) / 4);
saying that:
It's not in the correct format.
Can someone help me out here?

You add your strings with the currency symbol. If you want to parse the string back to a double (but it is better use a decimal) you need to tell the conversion that you have that symbol and ignore it
private void listFinances_SelectedIndexChanged(object sender, EventArgs e)
{
string TotalPrice = listFinances.SelectedItem.ToString();
decimal stateIncentive = decimal.Parse(TotalPrice, NumberStyles.Currency, CultureInfo.CurrentCulture) / 4);
txtStateTax.Text = stateIncentive.ToString();
}
I have used decimal instead of double because the decimal type is more adapt to handle money values. I suggest to make the same change in the for..loop that fill the list (Just use the suffix m to specify constant decimal values (IE. 4.25m and 0.05m)

You are trying to convert a currency string to double so you should Try like this:
double stateIncentive = (Double.Parse(TotalPrice, System.Globalization.NumberStyles.Currency) / 4);
Or would be better if using decimal (Read this to know why):
decimal stateIncentive = (decimal.Parse(TotalPrice, System.Globalization.NumberStyles.Currency) / 4);
The style parameter defines the style elements (such as white space, thousands separators, and currency symbols) refer to MSDN:Double.Parse Method (String, NumberStyles)

Related

How to get the next decimal given a decimal/precision

I want to determine the next decimal after a certain decimal programmatically.
For example, I have the decimal 0.0000041
I want to programmatically generate 0.0000042 in a function.
If I ran the function again after running it with 0.0000042 the new number would be 0.0000043
If I ran the function with the decimal being 0.0000049 the new number would be 0.0000050 etc....
Is there a way to do this?
I do not know where to start or what references to look at to do something like this.
Thank you.
You seem to be looking for something like this: (Check below if you want to specify the precision manually)
static decimal GetNextDecimal(decimal input)
{
int count = BitConverter.GetBytes(decimal.GetBits(input)[3])[2];
return input + (1m / (decimal)Math.Pow(10, count));
}
Usage:
decimal num1 = 0.0000041m;
decimal num2 = 0.00002m;
decimal next = GetNextDecimal(num1);
decimal next2 = GetNextDecimal(num2);
Console.WriteLine(next);
Console.WriteLine(next2);
Output:
0.0000042
0.00003
I used a little help of this answer to get the number of the decimal places.
If you originally wanted to specify the precision manually, you can use the following instead:
static decimal GetNextDecimal(decimal input, int precision)
{
return input + (1m / (decimal)Math.Pow(10, precision));
}
..which allows you to do something like this:
decimal num1 = 0.003m;
decimal next = GetNextDecimal(num1, 3);
decimal next2 = GetNextDecimal(num1, 4);
Console.WriteLine(next);
Console.WriteLine(next2);
Output:
0.004
0.0031

How to convert the text from a label into double

I am new to C# and just started to learn how to code. I was trying to convert and sum an amounts for several items displayed in a label, then displays the total in another label.I used parse to convert the values to double ,but I've frequently got an error message saying that"cannot implicitly convert type int to string.Here is a sample of my code.
int Cost;
double total = 0;
costLabel.Text = Convert.ToInt32(priceLabel2.Text);
Cost = int.Parse(priceLabel2.Text);
total += double.Parse(priceLabel2.Text);
costLabel.Text = total.ToString("c");
can any one help me to solve this problem?
Please, mind types; your code amended:
// Are you sure that price is integer? What about 4.95$?
// More natural choice is double (decimal is the best for the currency)
double Cost;
// Let's preserve double (but decimal is a better choice)
double total = 0;
// string assigned to string; no Convert.ToInt32
// It's useless line, however, since costLabel.Text = total.ToString("c");
// will rewrite the label
costLabel.Text = priceLabel2.Text;
// Since cost is not an integer value
Cost = double.Parse(priceLabel2.Text);
// You don't want to parse twice
total += Cost;
costLabel.Text = total.ToString("c");
A better choice is to use decimal for currency:
decimal total = 0m;
//TODO: it seem's that you want to add some logic here; otherwise total == cost
decimal cost = decimal.Parse(priceLabel2.Text);
total += cost;
costLabel.Text = total.ToString("c");
The problem is in the line costLabel.Text = Convert.ToInt32(priceLabel2.Text);. You have a lot of unnecessary code, so it could all be simplified to the following:
double total = double.Parse(priceLabel2.Text);
costLabel.Text = total.ToString("c");
You are assigning integers to strings, that won't work. You are also performing multiple operations on the same input. For currencies, you must use decimal since that is a safer (more precise) data type.
decimal total = 0;
...
decimal price = Convert.ToDecimal(priceLabel2.Text);
total += price;
costLabel.Text = total.ToString("c");
If you want to validate the input first, you should use decimal.TryParse:
if (decimal.TryParse(priceLabel2.Text, out decimal price))
{
total += price;
}
else
{
MessageBox.Show("Input is not a valid decimal.");
}
costLabel.Text property type is a string.
costLabel.Text = priceLabel2.Text;
costlLabel.Text is a string and you try to give it an integer value:
costLabel.Text = Convert.ToInt32(priceLabel2.Text);
use this instead:
costLabel.Text = priceLabel2.Text;

Need only 2 digits after decimal point

I want my function to return value with only 2 decimal places. I have tried following code :
private static double CalculateSlabTax(int nSlabStartTaxable,
int nSlabEndTaxable,
float fSlabRate)
{
double dblSlabResult = 0;
try
{
dblSlabResult = (nSlabStartTaxable - nSlabEndTaxable) * fSlabRate;
dblSlabResult = Math.Round(dblSlabResult , 2);
return dblSlabResult;
}
catch (Exception)
{
return -1;
}
}
Expected output is : dblSlabResult = ####.## - two digits (eg. 1002.05)
Getting output as : eg. dblSlabResult = 1002.1
To represent use formatting. In your case exactly two digits after decimal point means "F2" format string
double source = 1234.56789;
// 1234.57
var result = source.ToString("F2");
Very simple. Try this
public double UptoTwoDecimalPoints(double num)
{
var totalCost = Convert.ToDouble(String.Format("{0:0.00}", num));
return totalCost;
}
The # character is an optional digit placeholder. Use 0 to enforce digits when converting to string:
string.Format("{0:#.##}", 1002.1) == "1002.1"
string.Format("{0:0.00}", 1002.1) == "1002.10"
Don't expect a specific count of digits when rounding float or double. They are just numbers, independent of their string format.
What inputs are you using? Math.Round should be working correctly, which suggests that the line above is returning a double with only 1 significant figure.

Comparing values from dataGridView tables in VS2010 - C#

I have written a code that displays 6 DataGridView tables with values from excel that contain exchange rates for euros and us dollars from 6 different banks. The exchange rates are imported from excel file. Now i have to compare each of them and display the min value for euro buy rate (Куповен курс) and max value for sell rate (Продажен/Откупен курс) and min value for dollar buy rate (Куповен курс) and max value for sell rate (Продажен/Откупен курс). I need some help with C# code that will compare those values and display them in a TextBox by clicking the Compare button.
Here is pic from my app:
http://uploadpic.org/v.php?img=CYRmqhbE6F
I tried with this code, but give me error:
private void button7_Click(object sender, EventArgs e)
{
string s = dataGridView1.Rows[1].Cells[1].Value.ToString();
string t = dataGridView2.Rows[0].Cells[6].Value.ToString();
string k = dataGridView3.Rows[0].Cells[1].Value.ToString();
string l = dataGridView4.Rows[0].Cells[4].Value.ToString();
string m = dataGridView5.Rows[0].Cells[2].Value.ToString();
string n = dataGridView6.Rows[0].Cells[3].Value.ToString();
string[] kupoven = new string[] { s,t,k,l,m,n};
int length = kupoven.Length;
int last = length - 1;
int largest = kupoven[];
for (int i = 1; i <= length / 2; i++)
{
if (kupoven[i] > kupoven[last] && kupoven[i] > largest) largest = arr[i];
else if (kupoven[last] > largest) largest = kupoven[last];
last--;
}
return largest;
}
With this i put all euro values in strings(s,t,k,l,m,n), then i put them in array, and then i try to get the max value from the array. I think the problem is with type string.
That code you posted most likely doesn't compile... you should always post code that compiles, unless your question is about code that's not compiling. I would strongly recommend that you try to post sscce compliant questions: http://sscce.org/
With that said, if you want the maximum value I would do something along the lines:
private void button7_Click(object sender, EventArgs e)
{
double s = double.Parse(dataGridView1.Rows[1].Cells[1].Value.ToString());
double t = double.Parse(dataGridView2.Rows[0].Cells[6].Value.ToString());
double k = double.Parse(dataGridView3.Rows[0].Cells[1].Value.ToString());
double l = double.Parse(dataGridView4.Rows[0].Cells[4].Value.ToString());
double m = double.Parse(dataGridView5.Rows[0].Cells[2].Value.ToString());
double n = double.Parse(dataGridView6.Rows[0].Cells[3].Value.ToString());
double[] kupoven = new double[] { s,t,k,l,m,n};
double max = kupoven.Max();
}
Of course, that would only be store the maximum value in the local variable max. To display the max in a text box you would have to write some more code. I also feel like that simply displaying the maximum value may not be sufficient, given that you're comparing the exchange rate between different banks.

converting integer to decimal with precision value

how to make a text box to accept only decimal value with precision.
example.if the text box value is 12 .how to convert it to 12.00
and if it is 12.00 it must remain same..
thanks in advance.
You want to use a NumericUpDown-Control.
Edit: But to answer your question. To make TextBox-Control only accept numeric values, you'd have to suppress every key you do not want, and after that convert the input into a Decimal.
Decimal value = Convert.ToDecimal(this.yourTextBox.Text);
Or the fail-safe way:
Decimal value = 0;
String toParse = this.yourTextBox.Text;
if(!Decimal.TryParse(toParse, out value) {
// The user managed to break it...
}
A simple, fixed width variant is:
textBox1.Text = String.Format("{0,12:0.00}", textBox1.Text);
0 = first value (in this case
textBox1.Text)
12 = minimal width
0.00 = decimal (i.e. you could use #) find out more variants with
String.Format on msdn
Add an Event to the TextBoxChanged:
public void On_textbox1TextChanged(object sender, EventArgs e)
{
Double dblVal = 0;
if(Double.TryParse(this.textbox1.Text, ref dblVal))
{
this.textbox1.Text = dblVal.ToString("N2"); // Prints two 2 decimal places
}
else { /* Handle invalid value */ }
}
I would do a combination of the above on text change, and string formatting, but also go with a MASKED textbox. That will allow you to put in an expected mask to allow too.

Categories