Regular Expression with specific required numbers on both sides of decimal point - c#

I am trying to figure out a regular expression for an asp.net RequiredFieldValidator that validates decimal values from 1.001 to 99.9999.
This means every value greater than or equal to 1.001 and less than or equal to 99.9999.
The closest I have managed is:
(?=\d+(?:\.\d+)?$)(?![0\.]+$).{1,7}$
This still allows 0.1 and 1.0001, how do I prevent these values?

You can use negative lookaheads for that task:
^0*(?!1(?:\.0+)?$)(?!1\.000)(?!99\.9999.*[1-9])[1-9][0-9]?(?:\.[0-9]+)?$
Demo

I don't know asp.net, but maybe you could use something like this?
[1-9][0-9]?\.[0-9]{2}[1-9][0-9]?
However, maybe converting this to float and checking its inside the interval would do the trick, without the use of regexp...

Related

Rounding of float values

I have the double value like 12.256852651 and I want to display it as 12.257 as a float number without converting it in to a string type.
How can I do it in C# ?
I'd first convert to Decimal and then use Math.Round on the result. This conversion is not strictly necessary, but I always feel a bit uneasy if I round to decimal places while using binary floating points.
Math.Round((Decimal)f, 3, MidpointRounding.AwayFromZero)
You should also look into the choice of MidpointRounding, since by default this uses Banker's round, which is not what you are used to from school.
If you want to display it, it will be a string and that's what you need to use.
If you want to round in order to use it later in calculations, use Math.Round((decimal)myDouble, 3).
If you don't intend to use it in calculation but need to display it, use double.ToString("F3").

How to Output a Double Value with all the Decimal Places in Debugger or Console

I wish to extract double value completely when I am debugging an application, so that I can use it to construct a test case to feed into my geometry algorithm.
How to extract the double value out-- down to very last decimal places allowed by the double datatypes in C#-- and output it in either debugger windows, or using Console.WriteLine command?
Edit: My problem is that the algorithm that takes the double value as input will only fail if I insist of input the whole double value, right down to the very last digit. And since I want to reproduce it in a test case, that's why I would need such a full representation of the double value.
I have a DoubleConverter class which does exactly what you want, by the sounds of it. Use it like this:
string text = DoubleConverter.ToExactString(doubleValue);
You need to make sure you understand that just because the output has a large number of digits, that doesn't mean it has that much precision. You may want to read my article on binary floating point in .NET for more information - or you may be aware of all of this to start with, of course.
Note that if you only want a string value which can be round-tripped, you don't need any extra code - just use the "r" format specifier:
string text = doubleValue.ToString("r");
I agree with Jackson Pope's general approach of using tolerance in equality comparisons for tests, but I do find it useful sometimes to see the exact value represented by a double. It can make it easier to understand why a particular calculation has come out one way or another.
Instead of trying to output a binary number as a decimal number to a very large number of decimal places and do an exact comparison, instead do a comparison with an epsilon value that is your acceptable error and set epsilon to be very small. E.g.
double epsilon = Math.Abs(actual - expected);
Assert.That(epsilon, Is.LessThan(0.000000000001);

.NET decimal.Negate vs multiplying by -1

Are there any differences between decimal.Negate(myDecimal) and myDecimal * -1 (except maybe readability)?
I suspect Negate exists because there's a unary minus operator (op_UnaryNegation), and it's good practice to have methods representing the equivalent functionality so that languages which don't support operator overloading can still achieve the same result.
So instead of comparing it with myDecimal * -1 it may be helpful to think of it as being an alternative way of writing -myDecimal.
(I believe it's also optimised - given the way floating point works, negating a value is much simpler than normal multiplication; there's just a bit to flip. No need to perform any actual arithmetic.)
If you look in the .NET source with .NET Reflector, you will see the following:
(getting coffee until it finally opens..)
public static decimal Negate(decimal d)
{
return new decimal(d.lo, d.mid, d.hi, d.flags ^ -2147483648);
}
Looks like this is a fancy way to say -1 due to the way decimal internally works.
If you do *-1 it maps it to the following call:
FCallMultiply(ref result, yourNumber, -1M);
which will likely produce different IL code.
Personally, I find -myDecimal to be more readable than either (I'm no math geek, but I pretty sure all three are equivalent), but then again, I generally prefer compact notation.
If that is out, I'd go with Negate since I like to avoid magic numbers floating around in my code, and while the -1 as used there isn't really a magic number, it sure looks like one at first glance.
From MSDN, decimal.Negate:
Returns the result of multiplying the specified Decimal value by negative one.
No practical difference then, though readability is important.

C# - Math.Round

I am trying to understand how to round to the nearest tenths position with C#. For instance, I have a value that is of type double. This double is currently set to 10.75. However, I need to round and then truncate everything past the tenths position. In this case, I am seeking a value of 10.8. How do I round to the tenths position in C#?
Thank you!
Math.Round(yourNumber, 1)
The second parameter is number of decimal places to round to. In your case you want 1 decimal place as an end result.
You simply need to use the overload of Math.Round that takes the decimals parameter.
Math.Round(10.75, 1) // returns 10.8
Just for comparison:
Math.Round(10.75) // returns 11
Math.Round(10.75, 0) // returns 11
Math.Round(10.75, 2) // returns 10.75
Since you Used Math.Round() in your title, I'm going to assume you've already tried the basic Math.Round(10.75,1) approach and it returns something you don't expect. With that in mind, I suggest looking at some of the different overloads for the function, specifically one that accepts a MidPointRounding enum:
http://msdn.microsoft.com/en-us/library/f5898377.aspx
Do you really need to round it, or can you just format it for printing but allow the variable itself to hold its precision? Something like:
decimal value = 10.75;
value.ToString ("#.#");
If you just want to "cut" everything after the first decimal, this shoudl work :
return Math.Round(value * 10)/10

C# Wrong conversion using Convert.ChangeType()

I am using Convert.ChangeType() to convert from Object (which I get from DataBase) to a generic type T. The code looks like this:
T element = (T)Convert.ChangeType(obj, typeof(T));
return element;
and this works great most of the time, however I have discovered that if I try to cast something as simple as return of the following sql query
select 3.2
the above code (T being double) wont return 3.2, but 3.2000000000000002. I can't realise why this is happening, or how to fix it. Please help!
What you're seeing is an artifact of the way floating-point numbers are represented in memory. There's quite a bit of information available on exactly why this is, but this paper is a good one. This phenomenon is why you can end up with seemingly anomalous behavior. A double or single should never be displayed to the user unformatted, and you should avoid equality comparisons like the plague.
If you need numbers that are accurate to a greater level of precision (ie, representing currency values), then use decimal.
This probably is because of floating point arithmetic. You probably should use decimal instead of double.
It is not a problem of Convert. Internally double type represent as infinite fraction of 2 of real number, that is why you got such result. Depending of your purpose use:
Either Decimal
Or use precise formating {0:F2}
Use Math.Flor/Math.Ceil

Categories

Resources