Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumericUpDown.Value not rounded to DecimalPlaces

Suppose I have a NumericUpDown with DecimalPlaces = 2 .

The user types in "1.233" (having, unknown to them, accidentally tapped the "3" key twice) and then navigates away from the control. This input now appears in the control as "1.23". However, the Value property is now 1.233 . So, it appears to the user that they are using the value 1.23, when, in fact, they are using the value 1.233. Is there any way to make the NumericUpDown return the "correct" value: 1.23?

I understand that the DecimalPlaces property "... sets the number of decimal places to display", but then the user cannot determine what value will be used by simply reading the screen.

One way would be to always ignore the Value property of all NumericUpDowns and just use the Text property (hidden from IntelliSense) and do a decimal.Parse() on that property - but this just seems awkward. One other point is that if the user types in "1.233" and then navigates away from the control, then, when the ValueChanged event occurs the Text property is still "1.233".

like image 748
Clive Tooth Avatar asked Sep 05 '25 19:09

Clive Tooth


1 Answers

Yes. The Validating event is always useful to tweak data entry. Like this:

    private void numericUpDown1_Validating(object sender, CancelEventArgs e) {
        numericUpDown1.Value = Math.Round(numericUpDown1.Value, 
            numericUpDown1.DecimalPlaces, MidpointRounding.AwayFromZero);
    }
like image 77
Hans Passant Avatar answered Sep 08 '25 08:09

Hans Passant