简体   繁体   English

小数点前加零

[英]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). 例如(如果我在文本框中输入.2,它必须显示为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" . 字符串display现在包含"0.42"

You might want to use the Double.TryParse method to handle when the input is not valid. 您可能要使用Double.TryParse方法来处理输入无效的情况。

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: 生成一个函数,在其中编写一个简单的if结构,类似于以下结构:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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