Remove number from a textbox - c#

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());
}

Related

convert string from database to double

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:'

Simple addition string to int with C#

I have knowledge in PHP and I want to learn C # language but I do not even do simple addition.
I want to get the value of a ComboBox, convert this value to int and be able to add another value
Despite the conversion done, I have an error : Can not convert type "int" to "string.
My code :
private void btnValidate_click(object sender, RoutedEventArgs e)
{
int number = Test();
}
int Test()
{
string day = DayBirth.Text;
int number;
bool isNumeric = int.TryParse(day, out number);
if (isNumeric == false)
{
Resultat1.Text = "This is not a number";
}
else
{
Resultat1.Text = number + 10;
}
return number;
}
Thank you
The issue is that Resultat1.Text is expecting a string, not an int. You can do
Resultat1.Text = (number+10).ToString();
and it should work.
what you need to do is Converting your number to string after addition
Resultat1.Text = (number + 10).ToString;
Text property accept string value not integer so after addition you have to convert it as string
Resultat1.Text = (number + 10).ToString();

Avoid round off decimals in Datagridview control

In the Datagridview I have a column "C" which is product of Column "A" and "B".
Example
Column A Value - 8.14
Column B Value - 0.2
Now the column C value is 12.296 and after decimal I want to show first two numbers like
12.29 without rounding to 12.30.
Below is the code i used to achieve the above result.
public class CustomFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
// Check whether this is an appropriate callback
if (!this.Equals(formatProvider))
return null;
if (arg == null) return null;
string numericString = arg.ToString();
decimal result = 0;
if (Decimal.TryParse(numericString, out result))
{
return ((Math.Truncate(result * 100)) / 100).ToString();
}
else
{
return null;
}
}
}
private void gvItemDetails_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
try
{
if (e.ColumnIndex == gvItemDetails.Columns["Vat Amount"].Index)
{
gvItemDetails[e.ColumnIndex, e.RowIndex].Value = String.Format(new CustomFormatter(), "{0}", e.Value);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When i put a break point on cellformatting code..i can see the code is repeated continously but not returning any stackoverflow exception. When i remove the breakpoint its working.
Can you please advice what might be the problem or suggest any other alternative to prevent it from rounding an show 12.29 not 12.30.
Thanks,
Prathap.
First, i tried to use the same method which you used. It works perfectly fine for me and produces desired "12.29".
string numericString = "12.2963";
string truncatedString = string.Empty;
decimal result = 0;
if (Decimal.TryParse(numericString, out result))
{
truncatedString = ((Math.Truncate(result * 100)) / 100).ToString();
}
In case, above method doesn't work for you, another simple alternative would be to use string.substring (this will be useful only when intermediate decimal value is not required for you).
string numericString = "12.2963";
string truncatedString = string.Empty;value
int endIndex = numericString.IndexOf('.');
truncatedString = numericString.Substring(0, endIndex + 3);
Update:
Though i haven't tested it, you should be able to define format provider this way :
this.dataGridView1.Columns["XYZ"].DefaultCellStyle.FormatProvider = new CustomFormatter();
and for format (here format string will have pre-defined meaning) :
this.dataGridView1.Columns["XYZ"].DefaultCellStyle.Format = "c";
Update 2:
Unfortunately, even if you are using FormatProvider, you still need to handle cellformatting event; Check This.
Good news is that you don't need to use FormatProvider for this. Try following format, it should work for you:
this.dataGridView1.Columns["XYZ"].DefaultCellStyle.Format = "0.##";

c# check for integers in a textbox

I am trying to check if a textbox contains a number. The problem is that it always returns that it contains a non-numeric character.
I've tried several ways, but none of them seems to work.
One of the ways I've tried is:
if( Regex.IsMatch(tb.Text.Trim(), #"^[0-9]+$")) // tb.Text is the textbox
It does not matter what I enter in the textbox, it always returns that it contains a non-numeric character (I tried entering 1-9, 'a', 'b')
You could just parse the string to a specific number type, i.e.
double result;
if (!double.TryParse(tb.Text, out result))
{
//text is not a valid double;
throw new Exception("not a valid number");
}
//else the value is within the result variable
From your regex it seems that you need only integer values, so you should use int.TryParse or long.TryParse instead.
Quick and dirty test program:
void Main()
{
TestParse("1");
TestParse("a");
TestParse("1234");
TestParse("1a");
}
void TestParse(string text)
{
int result;
if (int.TryParse(text, out result))
{
Console.WriteLine(text + " is a number");
}
else
{
Console.WriteLine(text + " is not a number");
}
}
Results:
1 is a number
a is not a number
1234 is a number
1a is not a number
You could replace your Regex for this:
if(Regex.IsMatch(tb.Text.Trim(), #"[0-9]"))
Or for this:
if(Regex.IsMatch(tb.Text.Trim(), #"\d"))
you can use TryParse:
int value;
bool IsNumber = int.TryParse(tb.Text.Trim(), out value);
if(IsNumber)
{
//its number
}
private void btnMove_Click(object sender, EventArgs e)
{
string check = txtCheck.Text;
string status = "";
for (int i = 0; i < check.Length; i++)
{
if (IsNumber(check[i]))
status+="The char at "+i+" is a number\n";
}
MessageBox.Show(status);
}
private bool IsNumber(char c)
{
return Char.IsNumber(c);
}

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

Categories

Resources