简体   繁体   中英

Using Decimals in C#

 private void textBox1_TextChanged(object sender, EventArgs e)
        {
            int x = 0;
            if (Int32.TryParse(textBox1.Text, out x))
            {
                var y = 1000000;
                var answer = x * y;

                displayLabel2.Text = answer.ToString();
            }
            else
            {
                displayLabel2.Text = "error";
            }
        }

All of this code works. But I don't know how to use it if a decimal is inputed. Currently it reads numerical values fine and calculates them fine. But I need it to allow decimal points to be inputted. Ex. if someone inputed 4.7, then I need 4.7 to be multiplied by 1000000.

You need to use a number type that has precision. You can use either floating types ( double or float ) or the decimal type .

private void textBox1_TextChanged(object sender, EventArgs e)
{
    decimal x = 0;
    if (decimal.TryParse(textBox1.Text, out x))
    {
        var y = 1000000.0M;
        var answer = x * y;

        displayLabel2.Text = answer.ToString();
    }
    else
    {
        displayLabel2.Text = "error";
    }
}

You could use decimal instead of int:

decimal x = 0;
if (decimal.TryParse(textBox1.Text, out x))

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