Code Red > .NET
Convert string to non-negative, non-zero double with default value
Keith™:
I needed something like this .. comments and suggestions are welcome.
--- Code - C#: ---public double toPositiveDouble(string input, double def = 1){ double dv; if (!Double.TryParse(input, out dv){ //can't parse, return default dv = def; } else if ((dv + Math.Abs(dv)) == 0){ //value was negative, return default dv = def; }}
Atook:
Was there a reason for the Abs call instead of checking for <0?
Here's my take, the extension method might be considered bad form. :)
--- Code - C#: ---public static double ToPositiveDouble(this string input, double def = 1){ double dv; if (!Double.TryParse(input, out dv)){ //can't parse, return default return def; } else if (dv<0) { //value was negative, return default dv = def; } return dv;} // usagestring d = "-36";double dv = d.ToPositiveDouble(42.0);
Keith™:
No, just a brain fart
Atook:
--- Quote from: Keith™ on June 17, 2017, 01:09:41 PM ---No, just a brain fart
--- End quote ---
Don't feel too bad, I hadn't had my coffee yet, realized I couldn't figure out how to check if a number was negative and google lead me here... 8-)
That's when I remembered my rule of no code before coffee..
kdub_nz:
How about :
--- Code - C#: ---void Main() { Console.WriteLine(IsNegative(-3.7)); Console.WriteLine(IsNegative(42)); //------- string ds = "36"; double dv = ToPositiveDouble(ds, 42.0); Console.WriteLine($"{ds} : =>{dv}"); //------- ds = "-36"; dv = ToPositiveDouble(ds, 42.0); Console.WriteLine($"{ds} : =>{dv}"); //------- ds = ""; dv = ToPositiveDouble(ds, 42.0); Console.WriteLine($"{ds} : =>{dv}"); //------- ds = "0"; dv = ToPositiveDouble(ds, 42.0); Console.WriteLine($"{ds} : =>{dv}");} public static double ToPositiveDouble(string input, double def = 1) { double dv; return (Double.TryParse(input, out dv) && !IsNegative(dv)) ? dv : def; } /// Zero is considered negative in this worldpublic static bool IsNegative<T>(T value) where T : struct, IComparable<T> { return value.CompareTo(default(T)) <= 0;}
True
False
36 : =>36
-36 : =>42
: =>42
0 : =>42
Revised : /// Zero is considered negative in this world
Navigation
[0] Message Index
[#] Next page
Go to full version