convert string from database to double - c#

In my program I am using a database containing a Time (string previousTimeVASN).
I have a timer to clock total seconds. i would like to display the sum of previousTimeVASN + the total seconds.
I have error showing:
"System.FormatException: 'Input string was not in a correct format.'" at line: double test1 = Convert.ToDouble(previousTimeVASN);
any suggestion are much appreicated.
private void sNbtn_Click(object sender, RoutedEventArgs e)
{
TabControl.SelectedIndex = 1;
dtVASN.Tick += new EventHandler(dtVASN_Tick);
dtVASN.Interval = new TimeSpan(0, 0, 0, 0, 1);
}
void dtVASN_Tick(object sender, EventArgs e)
{
if (swVASN.IsRunning)
{
TimeSpan tsVASN = swVASN.Elapsed;
double test = tsVASN.TotalSeconds;
double test1 = Convert.ToDouble(previousTimeVASN);
txtVASN.Text = (test + test1).ToString();
}
}

The method Convert.ToDouble will throw FormatException if value is not a number in a valid format. You are getting the same here means either the value in previousTimeVASN is not a number or it is not in the expected format. Here is an alternate option for you to check whether the conversion is possible or not, that is, Double.TryParse Method
Converts the string representation of a number in a specified style
and culture-specific format to its double-precision floating-point
number equivalent. A return value indicates whether the conversion
succeeded or failed.
So the code can be revamped as like the following:
if (swVASN.IsRunning)
{
TimeSpan tsVASN = swVASN.Elapsed;
double test = tsVASN.TotalSeconds;
double test1;
Double.TryParse(previousTimeVASN, out test1);
txtVASN.Text = (test + test1).ToString();
}
if you want to alert the user that the second number is not valid then you can use the return value of parse like the following:
if(Double.TryParse(previousTimeVASN, out test1))
txtVASN.Text = (test + test1).ToString();
else
txtVASN.Text = "previous Time VASN is not valid:'

Related

Simple Calculator, System.FormatException

I'm trying to make a simple calculator and its fully working but when I calculate without a = button, my program completely crashes and gives the error:
System.FormatException: 'Input string was not in correct format.'
This is the code that it throws an error to:
second = double.Parse(aNumber);
// the strings and doubles:
String aNumber = "";
double first = 0.0;
b will be true or false if the try parse worked
d will contain the double or 0 if it fails
change anum to a valid number to test.
String anum = "";
double d = 0.0;
bool b = double.TryParse(anum, out d);
double.Parse will throw an exception if the input is not valid. So you either need to use try catch - or the preferred way would be to use double.TryParse as below. The value of y below will be set to the value if TryParse returns true.
class Program
{
static void Main(string[] args)
{
// This will cause an exception
var someString = "SomeValue";
var x = double.Parse(someString); // Comment this line out to run this example
// This will work
double y;
if (double.TryParse(someString, out y))
{
Console.WriteLine(someString + " is a valid decimal");
}
else
{
Console.WriteLine(someString + " is not a valid decimal");
}
someString = "14.7";
if (double.TryParse(someString, out y))
{
Console.WriteLine(someString + " is a valid decimal");
}
else
{
Console.WriteLine(someString + " is not a valid decimal");
}
}
}

pay money and changed

The problem of my code is if I put value in pay money(textbox) and I turned to zero giving me an error
System.FormatException: 'Input string was not in a correct format.'
This is my code :
private void txtPM_TextChanged(object sender, EventArgs e)
{
string fee = lblFee.Text.Trim();
string pm = txtPM.Text.Trim();
int number = Convert.ToInt32(fee);
int number2 = Convert.ToInt32(pm);
int minus = number2 - number;
txtChange.Text = minus.ToString().Trim();
}
I will put here the form
I hope you can help me thanks guys
You may need Convert.ToDecimal() if you are working with monetary values specified as decimals. (I second the empty and null checking suggestions)
Update for clarification:
Currently, you are converting string to Int32 with the following:
int number = Convert.ToInt32(fee);
int number2 = Convert.ToInt32(pm);
You can instead convert to decimal with the following:
decimal number = Convert.ToDecimal(fee);
decimal number2 = Convert.ToDecimal(pm);
Update2 (full method updated with null and empty checks):
private void txtPM_TextChanged(object sender, EventArgs e)
{
string fee = lblFee.Text.Trim();
string pm = txtPM.Text.Trim();
decimal number = 0;
decimal number2 = 0;
if(!string.IsNullOrWhiteSpace(fee)) number = Convert.ToDecimal(fee);
if(!string.IsNullOrWhiteSpace(pm)) number2 = Convert.ToDecimal(pm);
decimal minus = number2 - number;
txtChange.Text = minus.ToString().Trim();
}
Use the decimal type because it's more appropriate for financial and monetary calculations. To avoid the exception use decimal.TryParse. If the strings pm and fee are not in the right format decimal.TryParse will return zero and no exception will be thrown. You can also remove the Trim() on the last line.
private void txtPM_TextChanged(object sender, EventArgs e)
{
string fee = lblFee.Text.Trim();
string pm = txtPM.Text.Trim();
decimal number;
decimal.TryParse(fee, out number);
decimal number2;
decimal.TryParse(pm, out number2);
decimal minus = number2 - number;
txtChange.Text = minus.ToString();
}
You can use TryParse as already pointed out in the duplicate.
Also it makes more sense to use decimal when working with monetary values.
private void txtPM_TextChanged(object sender, EventArgs e)
{
decimal.TryParse(lblFee.Text, out decimal number);
decimal.TryParse(txtPM.Text, out decimal number2);
txtChange.Text = (number2 - number).ToString();
}
When using C# 6.0 or earlier you have to declare the variables in a separate statement:
private void txtPM_TextChanged(object sender, EventArgs e)
{
decimal number;
decimal.TryParse(lblFee.Text, out number);
decimal number2;
decimal.TryParse(txtPM.Text, out number2);
txtChange.Text = (number2 - number).ToString();
}

Getting the sum of numbers in a listbox?

Screenshot of the Form First time poster, and im in need of some help here. I am working on a program that calculates an athletes salary after hiring agents, lawyers, agents, etc. I have a listbox that displays the salary*the constant percentage of the agent. I CANNOT seem to get the sum of the numbers entered so i can subtract them from the total salary and display it in a label. I would love some help, very new to C#.
The area in question is commented out under the Switch
public partial class athleteForm : Form
{
public athleteForm()
{
InitializeComponent();
}
const decimal LAWYER_PERCENT = 0.10m;
const decimal AGENT_PERCENT = 0.05m;
const decimal PA_PERCENT = 0.03m;
const decimal TRAINER_PERCENT = 0.07m;
const string LAWYER_STRING = "Lawyer";
const string AGENT_STRING = "Agent";
const string PA_STRING = "Personal Assistant";
const string TRAINER_STRING = "Trainer";
string profFirstName;
string profLastName;
string profSelect;
decimal profPay;
public void athleteForm_Load(object sender, EventArgs e)
{
}
public void profAddButton_Click(object sender, EventArgs e)
{
decimal startingSalary = Convert.ToDecimal(startingSalaryText.Text);
profFirstName = profFirstNameText.Text;
profLastName = profLastNameText.Text;
profSelect = profComboBox.GetItemText(profComboBox.SelectedItem);
decimal lawyerPay = startingSalary * LAWYER_PERCENT;
decimal agentPay = startingSalary * AGENT_PERCENT;
decimal trainerPay = startingSalary * TRAINER_PERCENT;
decimal paPay = startingSalary * PA_PERCENT;
switch (profComboBox.GetItemText(profComboBox.SelectedItem))
{
case "Lawyer":
profPay = lawyerPay;
break;
case "Agent":
profPay = agentPay;
break;
case "Trainer":
profPay = trainerPay;
break;
case "Personal Assistant":
profPay = paPay;
break;
}
profListBox.Items.Add(profFirstName + " " + profLastName + " " + profSelect);
profPayList.Items.Add("$ " + profPay);
//decimal sumOfListbox =
// (from string S in profPayList.Items
// select Convert.ToDecimal(S))
// .Sum();
decimal sum =
profPayList.Items
.Cast<string>()
.Sum(v =>
{
decimal d;
return decimal.TryParse(v, out d) ? d : 0m;
});
remainSalaryLabel.Text = (sum.ToString());
}
public void clearButton_Click(object sender, EventArgs e)
{
switch (MessageBox.Show("Are you sure you want to clear all professionals?",
"WonderWord",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question))
{
case DialogResult.Yes:
profListBox.Items.Clear();
profPayList.Items.Clear();
remainSalaryLabel.Text = " ";
break;
case DialogResult.No:
// "No" processing
break;
case DialogResult.Cancel:
// "Cancel" processing
break;
}
}
}
}
The problem is that you are storing your data as a string prefixed with a dollar sign ($). e.g. "$5";
When your are calculating the sum of all of your data, you are correctly using a decimal.TryParse to convert the string to a decimal. However, in this case, the TryParse will not succeed in extracting the number due to the dollar sign.
Therefore, your options for fix this are:
Remove the dollar sign before parsing;
Use the Decimal.TryParse overload that handles numberstyles and currency symbols;
Maintain a separate list of numbers to sum instead of storing them within the ListBox so you don't have to deal with the dollar sign. If you wish to still display the numbers, you can still bind the list of numbers to the ListBox and update whenever a new number is added.
Option 2 would be your best option for the current state of your code. Assuming you're dealing with US culture, your code will need to look similar to this:
NumberStyles style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
decimal sum = profPayList.Items
.Cast<string>()
.Sum(v =>
{
decimal d;
return decimal.TryParse(v, style, culture, out d) ? d : 0m;
});
Option 3 is what I would be going with if you have time to rewrite what you have as it will solve some other potentially issues with your code that could arise in the future.

C# Program Crashes When No Number In TextBox

I have a WPF Application in C# and for one of my textboxes, the input is taken and then automatically converted(Celsius to Fahrenheit). When you input a number, it works fine, but then once all the digits of the inputted number are removed, the program crashes. I guess this is because the input format is 'invalid' because it's just trying to convert nothing?
I'm stumped on how to work around this, any help would be appreciated, thanks!
This is my code within the application:
private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
tempC.MaxLength = 3;
Temperature T = new Temperature(celsius);
T.temperatureValueInCelcius = Convert.ToDecimal(tempC.Text);
celsius = Convert.ToDecimal(tempC.Text);
T.ConvertToFarenheit(celsius);
tempF.Text = Convert.ToString(T.temperatureValueInFahrenheit);
}
and this is the code from the API I have created:
public decimal ConvertToFarenheit(decimal celcius)
{
temperatureValueInFahrenheit = (celcius * 9 / 5 + 32);
return temperatureValueInFahrenheit;
}
You should call the method Decimal.TryParse that tries to convert the value and signal if the conversion is not possible.
if(Decimal.TryParse(tempC.Text, out celsius))
{
// Value converted correctly
// Now you can use the variable celsius
}
else
MessageBox.Show("The textbox cannot be converted to a decimal");
private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
Decimal temp;
if (!Decimal.TryParse(out temp, tempC.Text))
return;
...
Try this :
private void tempC_TextChanged(object sender, TextChangedEventArgs e)
{
if(tempC.Text = "")
return;
tempC.MaxLength = 3;
Temperature T = new Temperature(celsius);
T.temperatureValueInCelcius = Convert.ToDecimal(tempC.Text);
celsius = Convert.ToDecimal(tempC.Text);
T.ConvertToFarenheit(celsius);
tempF.Text = Convert.ToString(T.temperatureValueInFahrenheit);
}
Try Decimal.TryParse
Here is some examples
string value;
decimal number;
// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a floating-point value with a currency symbol and a
// thousands separator.
value = "$1,643.57";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse value in exponential notation.
value = "-1.643e6";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// Parse a negative integer value.
value = "-1689346178821";
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
// The example displays the following output to the console:
// 1643.57
// Unable to parse '$1,643.57'.
// Unable to parse '-1.643e6'.
// -1689346178821

Remove number from a textbox

I have this number in textbox "84,8441546842904" how to convert in 84,8 or 84,84 on button click event?
If by this you mean you want to parse the value and round it to a certain number of decimal places:
double value = Math.Round(double.Parse(textbox.Text), 2);
will parse the text and round it to 2 decimal places. You may need to use a System.Globalization.CultureInfo object when parsing to account for your local culture's number formatting.
See http://msdn.microsoft.com/en-us/library/75ks3aby.aspx
It almost looks like you are trying to trim the number to 1 or 2 precision (isn't the ',' used in some countries as the US '.'?). If this is what you're after, you can use Double.Parse to convert it to a Double and then look into the string format options described here to format it back to the textbox.
I use this kind of functions to validate user input.
This approach to the problem also respects user culture number format!
namespace Your_App_Namespace
{
public static class Globals
{
public static double safeval = 0; // variable to save former value!
public static bool isPositiveNumeric(string strval, System.Globalization.NumberStyles NumberStyle)
// checking if string strval contains positive number in USER CULTURE NUMBER FORMAT!
{
double result;
boolean test;
if (strval.Contains("-")) test = false;
else test = Double.TryParse(strval, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
// if (test == false) MessageBox.Show("Not positive number!");
return test;
}
public static string numstr2string(string strval, string nofdec)
// conversion from numeric string into string in USER CULTURE NUMBER FORMAT!
// call example numstr2string("12.3456", "0.00") returns "12.34"
{
string retstr = 0.ToString(nofdec);
if (Globals.isPositiveNumeric(strval, System.Globalization.NumberStyles.Number)) retstr = double.Parse(strval).ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
public static string number2string(double numval, string nofdec)
// conversion from numeric value into string in USER CULTURE NUMBER FORMAT!
// call example number2string(12.3456, "0.00") returns "12.34"
{
string retstr = 0.ToString(nofdec);
if (Globals.isPositiveNumeric(numval.ToString(), System.Globalization.NumberStyles.Number)) retstr = numval.ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
}
// Other Your_App_Namespace content
}
// This is the way how to use those functions
// function to call when TextBox GotFocus
private void textbox_clear(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// save original value
Globals.safeval = double.Parse(txtbox.Text);
txtbox.Text = "";
}
// function to call when TextBox LostFocus
private void textbox_change(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// text from textbox into sting with checking and string format
txtbox.Text = Globals.numstr2string(txtbox.Text, "0.00");
}
double i = 0;
if (double.TryParse(tbxNumber.Text,out i)) {
MessageBox.Show("number is " + i.ToString());
}

Categories

Resources