简体   繁体   中英

adding zero before decimal point

I want to enter floating point values to some of the record. So if i enter .(decimal point), the zero should be added before the decimal point. For example (if i enter .2 into the textbox, it has to display like 0.2). How it can be done?

Any help will be appreciated.

Anticipated thanks.

Just parse the string to a double, and convert it back to string, then it will be formatted with a leading zero. Example:

string input = ".42";
double value = Double.Parse(input, CultureInfo.InvariantCulture);
string display = value.ToString(CultureInfo.InvariantCulture);

The string display now contains "0.42" .

You might want to use the Double.TryParse method to handle when the input is not valid.

Assuming a textbox, in it's properties, go to events, double-click on Leave (Listed below focus). A function is generated, write a simple if structure inside it similar to one below:

private void textBox1_Leave(object sender, EventArgs e)
{
    if ((textBox1.Text.Trim()).StartsWith("."))
       textBox1.Text = "0" + textBox1.Text;
}

keypressevent

 // add zero before point
    public void addzerobefore(object sender, KeyPressEventArgs e)
    {
        TextBox add0txtbx = sender as TextBox;
        if ((add0txtbx.Text.Trim()).StartsWith("."))
        {

            add0txtbx.Text = "0"+add0txtbx.Text;
            add0txtbx.Select(add0txtbx.Text.Length, 0);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM