user3587709
user3587709

Reputation: 89

How to prevent double decimals in a C# calculator

I'm developing a calculator in C# and I have a button that inserts a decimal point into the number. I ran into a problem where it allows the user to insert multiple decimal points into the interface, which threw everything off. I cooked up this little statement:

if ((number % 1) > 0)
{
    richTextBox1.Text = richTextBox1.Text + "";
}
else
{
    richTextBox1.Text = richTextBox1.Text + ".";
}

Except it doesn't do anything! Will someone please show me a way to only allow one decimal point by fixing this statement?

Upvotes: 1

Views: 1486

Answers (2)

David
David

Reputation: 10708

Have you tried using Double.TryParse directly?

if(Double.TryParse(richTextBox1.Text, myDoubleValue) == false)
    richTextBox1.Text = lastGoodValue;
else
    lastGoodValue = richTextBox1.Text;

this will also, via TryParse, give your actual double variable the proper result. As long as this occurs every time richTextBox1.Text changes, the correction code should also cause the double value to remain good, since it'll trigger when Text is reverted to lastGoodValue.

Upvotes: 0

eshs
eshs

Reputation: 194

onButtonToInsertDecimalClick

    if richTextBox1.Text.Contains(".")
        return;

    else
        ... rest of code

Wouldn't this (pseudocode) work?

Upvotes: 5

Related Questions