Yggdrasil : Home of Nidhogg

.NET coding at the roots of the Great Tree of Life
posts - 83, comments - 269, trackbacks - 233

RangeValidator quirks

I've been busy for weeks, hence the lack of post on this weblog. Here's a little one on strange things I noticed about RangeValidator and Double.

A few days ago I was trying to find the cause of an exception in an ASP.NET web application. It happened when I set a RangeValidator's Type to ValidationDataType.Double, then set the MaximumValue to Double.MaxValue.ToString(). I found two things :

  • Apparently, the real maximum value of a Double is 1.7976931348623157E+308. However, Double.MaxValue.ToString() produces 1.79769313486232E+308 which is not parsable with Double.Parse() because it is too big. The cause is that the default formatting for the Double type is 15 digits + exponent whereas the value itself has 17 fractional digits + exponent. When ToString() is called, it rounds the value and the result is a bigger number than the real value. Same goes for Double.Minimum value.

    Therefore, when you want to transform a Double to a string so that String.Parse works, use ToString("r"). This formatting ensures that a roundtrip Double->String->Double always works.

  • The RangeValidator uses a regular expression to validate the user input. You can see this with Reflector in the BaseCompareValidator.Convert method. The expression is : @"^\s*([-\+])?(\d+)?(\" + decimalSeparator + @"(\d+))?\s*$"; As you can see, it does not handle numbers formatted in scientific notation. Therefore, Double.MaxValue produces the exception I was getting : "The value '1.7976931348623157E+308' of the MaximumValue property of 'RangeValidator1' cannot be converted to type 'Double'."

    So the only Double values that can be used in a RangeValidator are the ones that can be written in string format without the scientific notation. I didn't check but I doubt you can write all Double numbers that way, there must be a limit to the number of digits in the string representation of a Double.

posted on Wednesday, December 15, 2004 6:38 PM

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Url
Comment   
Enter the code you see: