7

There's a way to force c# NumericUpDown to accept both comma and dot, to separate decimal values?

I've customized a textbox to do it (practically replacing dots with commas), but I'm surprised that there isn't another way..

This question explains how to change the separator, but I would like to use both!

Community
  • 1
  • 1
T30
  • 11,422
  • 7
  • 53
  • 57
  • Why do you want to be able to use both? If it is for several application deployment / users, you should use their local culture, because allowing comma AND dot as a decimal separator can be very confusing for some users. And the NumericUpDown does not allow this behaviour. You can force comma/dot conversion on valueChanged or keydown maybe? – Nicolas R Jun 19 '14 at 15:53
  • The problem is that using the other separator doesn't give an error: it simply ignores it making serious mistakes, and I want to avoid it. I'm working on a commercial software, and silently convert 10.22 to 1022 can be a big problem!! – T30 Jun 19 '14 at 16:08
  • @Nicolas R: Values accessible in valueChanged and keydown events are already converted (the wrong separator has been removed), and I can't go back to the inserted value... – T30 Jun 19 '14 at 16:15
  • Use KeyPress instead (look at my answer) – Nicolas R Jun 19 '14 at 16:21

3 Answers3

17

NumericUpDown control uses the culture of the operating system to use comma or dots as a decimal separator.

If you want to be able to handle both separators and consider them as a decimal separator (ie: not a thousand separator), you can use Validation or manual event treatment, for example:

private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar.Equals('.') || e.KeyChar.Equals(','))
        {
            e.KeyChar = ((System.Globalization.CultureInfo)System.Globalization.CultureInfo.CurrentCulture).NumberFormat.NumberDecimalSeparator.ToCharArray()[0];
        }
    }

In this example you will replace every dot and comma by the NumericDecimalSeparator of the current culture

Nicolas R
  • 13,812
  • 2
  • 28
  • 57
4

The solution provided by Nicolas R wouldn't work if you paste values into the NumericUpDown (via ClipBoard and Ctrl+V).

I suggest the following solution: The NumericUpDown Control has, like other Controls, a Text property. But, it is hidden from the designer and Intellisense. Using the Text property, you can write the ValueChanged event handler like this:

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    numericUpDown1.Text = numericUpDown1.Text.Replace(',', '.');
}

See also: https://msdn.microsoft.com/en-us/library/cs40s7ds.aspx

Community
  • 1
  • 1
0

For the standard NumericUpDown control, the decimal symbol is determined by the regional settings of the operating system.

CodeWeed
  • 971
  • 2
  • 21
  • 40