tags:

views:

159

answers:

5

In C#, I have a situation where I have two possible numbers in a textbox control.

The numbers can be either:

a) .xxxx

or

b) .xx

How do I write a condition that says, "If the textbox has 4 decimal places, then call this function, otherwise, if the textbox has 2 decimal places, then call this function."

Seems easy, but I don't know how to evaluate the decimal places.

Thanks much!

+1  A: 

Condition will evaluate true on two but not four decimal places:

Math.Round( 100*x ) == 100*x

EDIT: above condition works only for Decimal type. Well, following works for real numbers of all types:

( Math.Ceiling( 100 * x ) - 100 * x ) < 10e-8 )

EDIT: Well, if you are interested in strings then use following (extension string contains last point and subsequent digits/numbers):

System.IO.Path.GetExtension( input ).Length
Mikhail
This works if the OP is expecting a Decimal type. However, with a float, it doesn't. So, as long as OP checks it as a decimal, it should be fine.
keyboardP
So what happens if the user enters 1.0000
Stilgar
Ah yes, I didn't think of that.
keyboardP
See my comment above in the original post. What about doing something with String.Format?
Woody
+1  A: 

You can use String.IndexOf to get the index of the '.' and subtract that from the length.

Moron
+3  A: 
if(txtNumber.Text.Split(new[]{'.'})[1].Length == 2)
{
    //case b
}
else
{
    //case a
}

you may want to take the decimal separator from the system's current culture instead of hardcoding the dot.

Stilgar
+1  A: 

You could take advantage of a very obscure feature of the Decimal type. Its internal representation is a 96-bit number with an exponent. The exponent is equal to the number of digits in the fraction, even if the fractional digits are zero. Thus:

public static int GetFractionalDigits(string txt) {
  decimal value = decimal.Parse(txt);
  return (decimal.GetBits(value)[3] >> 16) & 0x7fff;
}

Use decimal.TryParse() if you need to validate the user input.

Hans Passant
+2  A: 

You can use Regex

new Regex(@"\.\d{2}$").IsMatch(input.Value)
Jader Dias
This regex will match two *or more* decimal places, so doesn't answer the question. You should use the `$` end-of-line anchor if you want to match *exactly* two decimal places.
LukeH
@Luke Thanks i corrected it
Jader Dias