float.TryParse(string, out float)

Here are the examples of the csharp api float.TryParse(string, out float) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

700 Examples 7

19 View Source File : ChatCommands.cs
License : MIT License
Project Creator : 0x0ade

public virtual ChatCMDArg Parse() {
            // TODO: Improve or rewrite. This comes from GhostNet, which adopted it from disbot (0x0ade's C# Discord bot).

            if (int.TryParse(String, out Int)) {
                Type = ChatCMDArgType.Int;
                Long = IntRangeFrom = IntRangeTo = Int;
                ULong = (ulong) Int;

            } else if (long.TryParse(String, out Long)) {
                Type = ChatCMDArgType.Long;
                ULong = (ulong) Long;

            } else if (ulong.TryParse(String, out ULong)) {
                Type = ChatCMDArgType.ULong;

            } else if (float.TryParse(String, out Float)) {
                Type = ChatCMDArgType.Float;
            }

            if (Type == ChatCMDArgType.String) {
                string[] split;
                int from, to;
                if ((split = String.Split('-')).Length == 2) {
                    if (int.TryParse(split[0].Trim(), out from) && int.TryParse(split[1].Trim(), out to)) {
                        Type = ChatCMDArgType.IntRange;
                        IntRangeFrom = from;
                        IntRangeTo = to;
                    }
                } else if ((split = String.Split('+')).Length == 2) {
                    if (int.TryParse(split[0].Trim(), out from) && int.TryParse(split[1].Trim(), out to)) {
                        Type = ChatCMDArgType.IntRange;
                        IntRangeFrom = from;
                        IntRangeTo = from + to;
                    }
                }
            }

            return this;
        }

19 View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH

public static float ToFloat(this object s, int? decimals = null)
    {
        if (s == null || s == DBNull.Value)
            return 0f;

        float.TryParse(s.ToString(), out float result);

        if (decimals == null)
            return result;

        return (float)Math.Round(result, decimals.Value);
    }

19 View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099

internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
        {
            if (valueRaw == null) return default(T);
            var type = typeof(T);
            var typename = type.ToString().TrimEnd(']');
            if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
            if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
            if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
            if (valueRaw.Length == 0) return default(T);

            string valueStr = null;
            if (type.IsValueType)
            {
                valueStr = encoding.GetString(valueRaw);
                bool isNullable = typename.StartsWith("System.Nullable`1[");
                var basename = isNullable ? typename.Substring(18) : typename;

                bool isElse = false;
                object obj = null;
                switch (basename)
                {
                    case "System.Boolean":
                        if (valueStr == "1") obj = true;
                        else if (valueStr == "0") obj = false;
                        break;
                    case "System.Byte":
                        if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
                        break;
                    case "System.Char":
                        if (valueStr.Length > 0) obj = valueStr[0];
                        break;
                    case "System.Decimal":
                        if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
                        break;
                    case "System.Double":
                        if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
                        break;
                    case "System.Single":
                        if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
                        break;
                    case "System.Int32":
                        if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
                        break;
                    case "System.Int64":
                        if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
                        break;
                    case "System.SByte":
                        if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
                        break;
                    case "System.Int16":
                        if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
                        break;
                    case "System.UInt32":
                        if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
                        break;
                    case "System.UInt64":
                        if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
                        break;
                    case "System.UInt16":
                        if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
                        break;
                    case "System.DateTime":
                        if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
                        break;
                    case "System.DateTimeOffset":
                        if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
                        break;
                    case "System.TimeSpan":
                        if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
                        break;
                    case "System.Guid":
                        if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
                        break;
                    default:
                        isElse = true;
                        break;
                }

                if (isElse == false)
                {
                    if (obj == null) return default(T);
                    return (T)obj;
                }
            }

            if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));

            if (valueStr == null) valueStr = encoding.GetString(valueRaw);
            if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
            return valueStr.ConvertTo<T>();
        }

19 View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab

internal static object ParseValue(Type type, string json) {
            if (type == typeof(string)) {
                if (json.Length <= 2)
                    return string.Empty;
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\\\", "\"\"").Replace("\\", string.Empty).Replace("\"\"", "\\");
            }
            if (type == typeof(int)) {
                int result;
                int.TryParse(json, out result);
                return result;
            }
            if (type == typeof(float)) {
                float result;
                float.TryParse(json, out result);
                return result;
            }
            if (type == typeof(double)) {
                double result;
                double.TryParse(json, out result);
                return result;
            }
            if (type == typeof(bool)) {
                return json.ToLower() == "true";
            }
            if (json == "null") {
                return null;
            }
            if (type.IsArray) {
                Type arrayType = type.GetElementType();
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                Array newArray = Array.CreateInstance(arrayType, elems.Count);
                for (int i = 0; i < elems.Count; i++)
                    newArray.SetValue(ParseValue(arrayType, elems[i]), i);
                splitArrayPool.Push(elems);
                return newArray;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
                Type listType = type.GetGenericArguments()[0];
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count });
                for (int i = 0; i < elems.Count; i++)
                    list.Add(ParseValue(listType, elems[i]));
                splitArrayPool.Push(elems);
                return list;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
                Type keyType, valueType;
                {
                    Type[] args = type.GetGenericArguments();
                    keyType = args[0];
                    valueType = args[1];
                }

                //Refuse to parse dictionary keys that aren't of type string
                if (keyType != typeof(string))
                    return null;
                //Must be a valid dictionary element
                if (json[0] != '{' || json[json.Length - 1] != '}')
                    return null;
                //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;

                var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 });
                for (int i = 0; i < elems.Count; i += 2) {
                    if (elems[i].Length <= 2)
                        continue;
                    string keyValue = elems[i].Substring(1, elems[i].Length - 2);
                    object val = ParseValue(valueType, elems[i + 1]);
                    dictionary.Add(keyValue, val);
                }
                return dictionary;
            }
            if (type == typeof(object)) {
                return ParseAnonymousValue(json);
            }
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                return ParseObject(type, json);
            }

            return null;
        }

19 View Source File : Utility.Convertor.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static object Convert(string typeStr,string typeValue)
            {
                Type type = Convert(typeStr);
                if (null!=type)
                {
                    var typeObject = Reflection.New(type);
                    if (type==typeof(int))
                    {
                        int v;
                        if (int.TryParse(typeValue,out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(Int16))
                    {
                        Int16 v;
                        if (Int16.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(Int64))
                    {
                        Int64 v;
                        if (Int64.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(float))
                    {
                        float v;
                        if (float.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(double))
                    {
                        double v;
                        if (double.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(decimal))
                    {
                        decimal v;
                        if (decimal.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(char))
                    {
                        char v;
                        if (char.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(string))
                    {
                        typeObject = typeValue;
                    }
                }
                return null;
            }

19 View Source File : Half.cs
License : MIT License
Project Creator : 91Act

public static bool TryParse(string value, out Half result)
        {
            float f;
            if (float.TryParse(value, out f))
            {
                result = (Half)f;
                return true;
            }

            result = new Half();
            return false;
        }

19 View Source File : CommandParameterHelpers.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static bool TryParsePosition(string[] parameters, out string errorMessage, out Position position, int startingElement = 0)
        {
            errorMessage = string.Empty;
            position = null;
            if (parameters.Length - startingElement - 1 < 1)
            {
                errorMessage = "not enough parameters";
                return false;
            }

            string northSouth = parameters[startingElement].ToLower().Replace(",", "").Trim();
            string eastWest = parameters[startingElement + 1].ToLower().Replace(",", "").Trim();


            if (!northSouth.EndsWith("n") && !northSouth.EndsWith("s"))
            {
                errorMessage = "Missing n or s indicator on first parameter";
                return false;
            }

            if (!eastWest.EndsWith("e") && !eastWest.EndsWith("w"))
            {
                errorMessage = "Missing e or w indicator on second parameter";
                return false;
            }

            if (!float.TryParse(northSouth.Substring(0, northSouth.Length - 1), out float coordNS))
            {
                errorMessage = "North/South coordinate is not a valid number.";
                return false;
            }

            if (!float.TryParse(eastWest.Substring(0, eastWest.Length - 1), out float coordEW))
            {
                errorMessage = "East/West coordinate is not a valid number.";
                return false;
            }

            if (northSouth.EndsWith("s"))
            {
                coordNS *= -1.0f;
            }

            if (eastWest.EndsWith("w"))
            {
                coordEW *= -1.0f;
            }

            try
            {
                position = new Position(coordNS, coordEW);
                position.AdjustMapCoords();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                errorMessage = $"There was a problem with that location (bad coordinates?).";
                return false;
            }
            return true;
        }

19 View Source File : MutationCache.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static MutationFilter BuildMutation(string filename)
        {
            var lines = ReadScript(filename);

            if (lines == null)
            {
                log.Error($"MutationCache.BuildMutation({filename}) - embedded resource not found");
                return null;
            }

            string prevMutationLine = null;
            string mutationLine = null;

            var mutationFilter = new MutationFilter();
            Mutation mutation = null;
            MutationOutcome outcome = null;
            EffectList effectList = null;

            var totalChance = 0.0M;

            var timer = Stopwatch.StartNew();

            foreach (var _line in lines)
            {
                var line = _line;

                var commentIdx = line.IndexOf("//");

                if (commentIdx != -1)
                    line = line.Substring(0, commentIdx);

                if (line.Contains("Mutation #", StringComparison.OrdinalIgnoreCase))
                {
                    prevMutationLine = mutationLine;
                    mutationLine = line;
                    continue;
                }

                if (line.Contains("Tier chances", StringComparison.OrdinalIgnoreCase))
                {
                    if (outcome != null && outcome.EffectLists.Last().Chance != 1.0f)
                        log.Error($"MutationCache.BuildMutation({filename}) - {prevMutationLine} total {outcome.EffectLists.Last().Chance}, expected 1.0");

                    mutation = new Mutation();
                    mutationFilter.Mutations.Add(mutation);

                    var tierPieces = line.Split(',');

                    foreach (var tierPiece in tierPieces)
                    {
                        var match = Regex.Match(tierPiece, @"([\d.]+)");
                        if (match.Success && float.TryParse(match.Groups[1].Value, out var tierChance))
                        {
                            mutation.Chances.Add(tierChance);
                        }
                        else
                        {
                            log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse tier chances for {mutationLine}: {tierPiece}");
                            mutation.Chances.Add(0.0f);
                        }
                    }

                    outcome = new MutationOutcome();
                    mutation.Outcomes.Add(outcome);

                    totalChance = 0.0M;

                    continue;
                }

                if (line.Contains("- Chance", StringComparison.OrdinalIgnoreCase))
                {
                    if (totalChance >= 1.0M)
                    {
                        if (totalChance > 1.0M)
                            log.Error($"MutationCache.BuildMutation({filename}) - {mutationLine} total {totalChance}, expected 1.0");

                        outcome = new MutationOutcome();
                        mutation.Outcomes.Add(outcome);

                        totalChance = 0.0M;
                    }

                    effectList = new EffectList();
                    outcome.EffectLists.Add(effectList);

                    var match = Regex.Match(line, @"([\d.]+)");
                    if (match.Success && decimal.TryParse(match.Groups[1].Value, out var chance))
                    {
                        totalChance += chance / 100;

                        effectList.Chance = (float)totalChance;
                    }
                    else
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line} for {mutationLine}");
                    }
                    continue;
                }

                if (!line.Contains("="))
                    continue;

                var effect = new Effect();

                effect.Type = GetMutationEffectType(line);

                var firstOperator = GetFirstOperator(effect.Type);

                var pieces = line.Split(firstOperator, 2);

                if (pieces.Length != 2)
                {
                    log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line}");
                    continue;
                }

                pieces[0] = pieces[0].Trim();
                pieces[1] = pieces[1].Trim();

                var firstStatType = GetStatType(pieces[0]);

                /*if (firstStatType == StatType.Undef)
                {
                    log.Error($"MutationCache.BuildMutation({filename}) - couldn't determine StatType for {pieces[0]} in {line}");
                    continue;
                }*/

                effect.Quality = ParseEffectArgument(filename, effect, pieces[0]);

                var hreplacedecondOperator = HreplacedecondOperator(effect.Type);

                if (!hreplacedecondOperator)
                {
                    effect.Arg1 = ParseEffectArgument(filename, effect, pieces[1]);
                }
                else
                {
                    var secondOperator = GetSecondOperator(effect.Type);

                    var subpieces = pieces[1].Split(secondOperator, 2);

                    if (subpieces.Length != 2)
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {line}");
                        continue;
                    }

                    subpieces[0] = subpieces[0].Trim();
                    subpieces[1] = subpieces[1].Trim();

                    effect.Arg1 = ParseEffectArgument(filename, effect, subpieces[0]);
                    effect.Arg2 = ParseEffectArgument(filename, effect, subpieces[1]);
                }

                effectList.Effects.Add(effect);
            }

            if (outcome != null && outcome.EffectLists.Last().Chance != 1.0f)
                log.Error($"MutationCache.BuildMutation({filename}) - {mutationLine} total {outcome.EffectLists.Last().Chance}, expected 1.0");

            timer.Stop();

            // scripts take about ~2ms to compile
            //Console.WriteLine($"Compiled {filename} in {timer.Elapsed.TotalMilliseconds}ms");

            return mutationFilter;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<int> ParseChanceTable_Int(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<int>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"(\d+),\s+([\d.]+)");

                if (!match.Success || !int.TryParse(match.Groups[1].Value, out var val) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((val, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<SpellId> ParseChanceTable_Spell(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<SpellId>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"SpellId.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out SpellId spell) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((spell, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<WeenieClreplacedName> ParseChanceTable_Wcid(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<WeenieClreplacedName>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"WeenieClreplacedName.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out WeenieClreplacedName wcid) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((wcid, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<bool> ParseChanceTable_Bool(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<bool>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"\(\s+([^,]+),\s+([\d.]+)");

                if (!match.Success || !bool.TryParse(match.Groups[1].Value, out var val) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((val, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<TreasureHeritageGroup> ParseChanceTable_Heritage(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<TreasureHeritageGroup>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"TreasureHeritageGroup.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureHeritageGroup heritage) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((heritage, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<TreasureItemType_Orig> ParseChanceTable_ItemType(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<TreasureItemType_Orig>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"TreasureItemType_Orig.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureItemType_Orig itemType) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((itemType, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<TreasureArmorType> ParseChanceTable_ArmorType(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<TreasureArmorType>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"TreasureArmorType.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureArmorType armorType) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((armorType, chance));
            }

            return chanceTable;
        }

19 View Source File : LootParser.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static ChanceTable<TreasureWeaponType> ParseChanceTable_WeaponType(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<TreasureWeaponType>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

                var match = Regex.Match(line, @"TreasureWeaponType.([^,]+),\s+([\d.]+)");

                if (!match.Success || !System.Enum.TryParse(match.Groups[1].Value, out TreasureWeaponType weaponType) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((weaponType, chance));
            }

            return chanceTable;
        }

19 View Source File : AnarchyStorage.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public float GetFloat(string key, float def)
        {
            float result;
            if (floats.TryGetValue(key, out result))
            {
                return result;
            }
            string val;
            if (allValues.TryGetValue(key, out val))
            {
                if (float.TryParse(val, out result))
                {
                    floats.Add(key, result);
                    return result;
                }
                return def;
            }
            else
            {
                SetFloat(key, def);
                return def;
            }
        }

19 View Source File : GameModeSetting.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void Apply()
        {
            forcedChange = false;
            if (nextFloats != null)
            {
                for (int i = 0; i < nextFloats.Length; i++)
                {
                    if (float.TryParse(floatStrings[i], out float val))
                    {
                        nextFloats[i] = val;
                    }
                }
            }
            if (nextIntegers != null)
            {
                for (int i = 0; i < nextIntegers.Length; i++)
                {
                    if (int.TryParse(integerStrings[i], out int val))
                    {
                        nextIntegers[i] = val;
                    }
                }
            }
            onApplyCallback(this, state, nextSelection, nextFloats, nextIntegers);
            appliedState = state;
            if (nextSelection >= 0)
            {
                appliedSelection = nextSelection + 1;
            }
            if (nextFloats != null)
            {
                for (int i = 0; i < nextFloats.Length; i++)
                {
                    appliedFloats[i] = nextFloats[i];
                    floatStrings[i] = nextFloats[i].ToString("F2");
                }
            }
            if (nextIntegers != null)
            {
                for (int i = 0; i < nextIntegers.Length; i++)
                {
                    appliedIntegers[i] = nextIntegers[i];
                    integerStrings[i] = nextIntegers[i].ToString();
                }
            }
            onStateChanged(this, state, false);
        }

19 View Source File : CommandArgs.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public bool TryGetFloat(string key, out float val)
        {
            if (HasValue(key))
            {
                return float.TryParse(flags[key], out val);
            }
            val = default;
            return false;
        }

19 View Source File : CommandArgs.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public bool TryGetFloat(int rawIndex, out float val)
        {
            return float.TryParse(RawArgs[rawIndex], out val);
        }

19 View Source File : GameModeSetting.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void Load()
        {
            IDataStorage storage = Settings.Storage;
            state = storage.GetBool(saveKey + "State", false);
            if (nextSelection >= 0)
            {
                nextSelection = storage.GetInt(saveKey + "Selection", nextSelection);
            }
            if (nextFloats != null)
            {
                floatStrings = new string[nextFloats.Length];
                appliedFloats = new float[nextFloats.Length];
                for (int i = 0; i < nextFloats.Length; i++)
                {
                    floatStrings[i] = storage.GetFloat(saveKey + "Float" + i.ToString(), nextFloats[i]).ToString();
                    if (!float.TryParse(floatStrings[i], out float val))
                    {
                        floatStrings[i] = nextFloats[i].ToString("F2");
                    }
                    else
                    {
                        nextFloats[i] = val;
                    }
                    appliedFloats[i] = nextFloats[i];
                }
            }
            if (nextIntegers != null)
            {
                integerStrings = new string[nextIntegers.Length];
                appliedIntegers = new int[nextIntegers.Length];
                for (int i = 0; i < nextIntegers.Length; i++)
                {
                    integerStrings[i] = storage.GetInt(saveKey + "Int" + i.ToString(), nextIntegers[i]).ToString();
                    if (!int.TryParse(integerStrings[i], out int val))
                    {
                        integerStrings[i] = nextIntegers[i].ToString();
                    }
                    else
                    {
                        nextIntegers[i] = val;
                    }
                    appliedIntegers[i] = nextIntegers[i];
                }
            }
        }

19 View Source File : GameModeSetting.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void Save()
        {
            IDataStorage storage = Settings.Storage;
            storage.SetBool(saveKey + "State", state);
            if (nextSelection >= 0)
            {
                storage.SetInt(saveKey + "Selection", nextSelection);
            }
            if (nextFloats != null)
            {
                for (int i = 0; i < nextFloats.Length; i++)
                {
                    if (float.TryParse(floatStrings[i], out float val))
                    {
                        nextFloats[i] = val;
                    }
                }
                for (int i = 0; i < nextFloats.Length; i++)
                {
                    storage.SetFloat(saveKey + "Float" + i.ToString(), nextFloats[i]);
                }
            }
            if (nextIntegers != null)
            {
                for (int i = 0; i < nextIntegers.Length; i++)
                {
                    if (int.TryParse(integerStrings[i], out int val))
                    {
                        nextIntegers[i] = val;
                    }
                }
                for (int i = 0; i < nextIntegers.Length; i++)
                {
                    storage.SetInt(saveKey + "Int" + i.ToString(), nextIntegers[i]);
                }
            }
        }

19 View Source File : ConfigFile.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public float GetFloat(string key)
        {
            float result;
            if (floats.TryGetValue(key, out result))
            {
                return result;
            }
            string val;
            if (allValues.TryGetValue(key, out val))
            {
                if (float.TryParse(val, out result))
                {
                    floats.Add(key, result);
                }
            }
            return result;
        }

19 View Source File : AnarchyExtensions.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static Vector3 ParseVector3(this string str)
        {
            if (!str.StartsWith("(") && !str.EndsWith(")"))
            {
                return Vectors.zero;
            }

            str = str.Replace("(", string.Empty).Replace(")", string.Empty);
            string[] toParse = str.Split(',');
            if (toParse.Length != 3)
            {
                return Vectors.zero;
            }

            Vector3 result = new Vector3();
            float.TryParse(toParse[0], out var val);
            result.x = val;
            float.TryParse(toParse[1], out val);
            result.y = val;
            float.TryParse(toParse[2], out val);
            result.z = val;
            return result;
        }

19 View Source File : Cannon.cs
License : GNU General Public License v3.0
Project Creator : aelariane

[RPC]
    public void SetSize(string settings, PhotonMessageInfo info)
    {
        bool isMasterClient = info.Sender.IsMasterClient;
        if (isMasterClient)
        {
            string[] array = settings.Split(new char[]
            {
                ','
            });
            bool flag = array.Length > 15;
            if (flag)
            {
                float a = 1f;
                GameObject gameObject = base.gameObject;
                bool flag2 = array[2] != "default";
                if (flag2)
                {
                    bool flag3 = array[2].StartsWith("transparent");
                    if (flag3)
                    {
                        float num;
                        bool flag4 = float.TryParse(array[2].Substring(11), out num);
                        if (flag4)
                        {
                            a = num;
                        }
                        foreach (Renderer renderer in gameObject.GetComponentsInChildren<Renderer>())
                        {
                            renderer.material = (Material)RCManager.Load("transparent");
                            bool flag5 = Convert.ToSingle(array[10]) != 1f || Convert.ToSingle(array[11]) != 1f;
                            if (flag5)
                            {
                                renderer.material.mainTextureScale = new Vector2(renderer.material.mainTextureScale.x * Convert.ToSingle(array[10]), renderer.material.mainTextureScale.y * Convert.ToSingle(array[11]));
                            }
                        }
                    }
                    else
                    {
                        foreach (Renderer renderer2 in gameObject.GetComponentsInChildren<Renderer>())
                        {
                            bool flag6 = !renderer2.name.Contains("Line Renderer");
                            if (flag6)
                            {
                                renderer2.material = (Material)RCManager.Load(array[2]);
                                bool flag7 = Convert.ToSingle(array[10]) != 1f || Convert.ToSingle(array[11]) != 1f;
                                if (flag7)
                                {
                                    renderer2.material.mainTextureScale = new Vector2(renderer2.material.mainTextureScale.x * Convert.ToSingle(array[10]), renderer2.material.mainTextureScale.y * Convert.ToSingle(array[11]));
                                }
                            }
                        }
                    }
                }
                float num2 = gameObject.transform.localScale.x * Convert.ToSingle(array[3]);
                num2 -= 0.001f;
                float y = gameObject.transform.localScale.y * Convert.ToSingle(array[4]);
                float z = gameObject.transform.localScale.z * Convert.ToSingle(array[5]);
                gameObject.transform.localScale = new Vector3(num2, y, z);
                bool flag8 = array[6] != "0";
                if (flag8)
                {
                    Color color = new Color(Convert.ToSingle(array[7]), Convert.ToSingle(array[8]), Convert.ToSingle(array[9]), a);
                    foreach (MeshFilter meshFilter in gameObject.GetComponentsInChildren<MeshFilter>())
                    {
                        Mesh mesh = meshFilter.mesh;
                        Color[] array2 = new Color[mesh.vertexCount];
                        for (int l = 0; l < mesh.vertexCount; l++)
                        {
                            array2[l] = color;
                        }
                        mesh.colors = array2;
                    }
                }
            }
        }
    }

19 View Source File : RCActionHelper.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public float returnFloat(object sentObject)
    {
        object parameters = sentObject;
        if (this.parameters != null)
        {
            parameters = this.parameters;
        }
        switch (this.helperClreplaced)
        {
            case 0:
                return (float)parameters;

            case 1:
                {
                    RCActionHelper helper = (RCActionHelper)parameters;
                    switch (this.helperType)
                    {
                        case 0:
                            return this.nextHelper.returnFloat(RCManager.intVariables[helper.returnString(null)]);

                        case 1:
                            return this.nextHelper.returnFloat(RCManager.boolVariables[helper.returnString(null)]);

                        case 2:
                            return this.nextHelper.returnFloat(RCManager.stringVariables[helper.returnString(null)]);

                        case 3:
                            return (float)RCManager.floatVariables[helper.returnString(null)];

                        case 4:
                            return this.nextHelper.returnFloat(RCManager.playerVariables[helper.returnString(null)]);

                        case 5:
                            return this.nextHelper.returnFloat(RCManager.replacedanVariables[helper.returnString(null)]);

                        default:
                            return 0f;
                    }
                }
            case 2:
                {
                    PhotonPlayer player = (PhotonPlayer)parameters;
                    if (player != null)
                    {
                        switch (this.helperType)
                        {
                            case 0:
                                return this.nextHelper.returnFloat(player.Properties["team"]);

                            case 1:
                                return this.nextHelper.returnFloat(player.Properties["RCteam"]);

                            case 2:
                                return this.nextHelper.returnFloat(player.Properties["dead"]);

                            case 3:
                                return this.nextHelper.returnFloat(player.Properties["isreplacedan"]);

                            case 4:
                                return this.nextHelper.returnFloat(player.Properties["kills"]);

                            case 5:
                                return this.nextHelper.returnFloat(player.Properties["deaths"]);

                            case 6:
                                return this.nextHelper.returnFloat(player.Properties["max_dmg"]);

                            case 7:
                                return this.nextHelper.returnFloat(player.Properties["total_dmg"]);

                            case 8:
                                return this.nextHelper.returnFloat(player.Properties["customInt"]);

                            case 9:
                                return this.nextHelper.returnFloat(player.Properties["customBool"]);

                            case 10:
                                return this.nextHelper.returnFloat(player.Properties["customString"]);

                            case 11:
                                return (float)player.Properties["customFloat"];

                            case 12:
                                return this.nextHelper.returnFloat(player.Properties["name"]);

                            case 13:
                                return this.nextHelper.returnFloat(player.Properties["guildName"]);

                            case 14:
                                {
                                    int iD = player.ID;
                                    if (RCManager.heroHash.ContainsKey(iD))
                                    {
                                        return ((HERO)RCManager.heroHash[iD]).transform.position.x;
                                    }
                                    return 0f;
                                }
                            case 15:
                                {
                                    int key = player.ID;
                                    if (RCManager.heroHash.ContainsKey(key))
                                    {
                                        return ((HERO)RCManager.heroHash[key]).transform.position.y;
                                    }
                                    return 0f;
                                }
                            case 16:
                                {
                                    int num7 = player.ID;
                                    if (RCManager.heroHash.ContainsKey(num7))
                                    {
                                        return ((HERO)RCManager.heroHash[num7]).transform.position.z;
                                    }
                                    return 0f;
                                }
                            case 17:
                                {
                                    int num8 = player.ID;
                                    if (RCManager.heroHash.ContainsKey(num8))
                                    {
                                        return ((HERO)RCManager.heroHash[num8]).rigidbody.velocity.magnitude;
                                    }
                                    return 0f;
                                }
                        }
                    }
                    return 0f;
                }
            case 3:
                {
                    replacedAN replacedan = (replacedAN)parameters;
                    if (replacedan != null)
                    {
                        switch (this.helperType)
                        {
                            case 0:
                                return this.nextHelper.returnFloat(replacedan.abnormalType);

                            case 1:
                                return replacedan.myLevel;

                            case 2:
                                return this.nextHelper.returnFloat(replacedan.currentHealth);

                            case 3:
                                return replacedan.transform.position.x;

                            case 4:
                                return replacedan.transform.position.y;

                            case 5:
                                return replacedan.transform.position.z;
                        }
                    }
                    return 0f;
                }
            case 4:
                {
                    RCActionHelper helper2 = (RCActionHelper)parameters;
                    RCRegion region = (RCRegion)RCManager.RCRegions[helper2.returnString(null)];
                    switch (this.helperType)
                    {
                        case 0:
                            return region.GetRandomX();

                        case 1:
                            return region.GetRandomY();

                        case 2:
                            return region.GetRandomZ();

                        default:
                            return 0f;
                    };
                }
            case 5:
                switch (this.helperType)
                {
                    case 0:
                        return Convert.ToSingle((int)parameters);

                    case 1:
                        return Convert.ToSingle((bool)parameters);

                    case 2:
                        {
                            string text = (string)parameters;
                            float num9;
                            if (float.TryParse((string)parameters, out num9))
                            {
                                return num9;
                            }
                            return 0f;
                        }
                    case 3:
                        return (float)parameters;

                    default:
                        return (float)parameters;
                }
            default:
                return 0f;
        }
    }

19 View Source File : CannonPropRegion.cs
License : GNU General Public License v3.0
Project Creator : aelariane

[RPC]
    public void SetSize(string settings, PhotonMessageInfo info)
    {
        if (info.Sender.IsMasterClient)
        {
            string[] array = settings.Split(new char[]
            {
                ','
            });
            bool flag = array.Length > 15;
            if (flag)
            {
                float a = 1f;
                GameObject gameObject = base.gameObject;
                bool flag2 = array[2] != "default";
                if (flag2)
                {
                    bool flag3 = array[2].StartsWith("transparent");
                    if (flag3)
                    {
                        float num;
                        bool flag4 = float.TryParse(array[2].Substring(11), out num);
                        if (flag4)
                        {
                            a = num;
                        }
                        foreach (Renderer renderer in gameObject.GetComponentsInChildren<Renderer>())
                        {
                            renderer.material = (Material)RCManager.Load("transparent");
                            bool flag5 = Convert.ToSingle(array[10]) != 1f || Convert.ToSingle(array[11]) != 1f;
                            if (flag5)
                            {
                                renderer.material.mainTextureScale = new Vector2(renderer.material.mainTextureScale.x * Convert.ToSingle(array[10]), renderer.material.mainTextureScale.y * Convert.ToSingle(array[11]));
                            }
                        }
                    }
                    else
                    {
                        foreach (Renderer renderer2 in gameObject.GetComponentsInChildren<Renderer>())
                        {
                            renderer2.material = (Material)RCManager.Load(array[2]);
                            bool flag6 = Convert.ToSingle(array[10]) != 1f || Convert.ToSingle(array[11]) != 1f;
                            if (flag6)
                            {
                                renderer2.material.mainTextureScale = new Vector2(renderer2.material.mainTextureScale.x * Convert.ToSingle(array[10]), renderer2.material.mainTextureScale.y * Convert.ToSingle(array[11]));
                            }
                        }
                    }
                }
                float num2 = gameObject.transform.localScale.x * Convert.ToSingle(array[3]);
                num2 -= 0.001f;
                float y = gameObject.transform.localScale.y * Convert.ToSingle(array[4]);
                float z = gameObject.transform.localScale.z * Convert.ToSingle(array[5]);
                gameObject.transform.localScale = new Vector3(num2, y, z);
                bool flag7 = array[6] != "0";
                if (flag7)
                {
                    Color color = new Color(Convert.ToSingle(array[7]), Convert.ToSingle(array[8]), Convert.ToSingle(array[9]), a);
                    foreach (MeshFilter meshFilter in gameObject.GetComponentsInChildren<MeshFilter>())
                    {
                        Mesh mesh = meshFilter.mesh;
                        Color[] array2 = new Color[mesh.vertexCount];
                        for (int l = 0; l < mesh.vertexCount; l++)
                        {
                            array2[l] = color;
                        }
                        mesh.colors = array2;
                    }
                }
            }
        }
    }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public float ToSingle(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                AddMessage(name, "值不能为空");
                Failed = true;
                return 0;
            }
            float vl;
            if (!float.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return 0;
            }
            return vl;
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public float ToSingle(string name, float def)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                return def;
            }
            float vl;
            if (!float.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return 0;
            }
            return vl;
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public float? ToNullSingle(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                return null;
            }
            float vl;
            if (!float.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return null;
            }
            return vl;
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public float ToSingle(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                AddMessage(name, "值不能为空");
                Failed = true;
                return 0;
            }

            if (!float.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return 0;
            }

            return vl;
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public float ToSingle(string name, float def)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name))) return def;
            if (!float.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return 0;
            }

            return vl;
        }

19 View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public float? ToNullSingle(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name))) return null;
            if (!float.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为小数");
                Failed = true;
                return null;
            }

            return vl;
        }

19 View Source File : CommandHelpers.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

internal static void TryParseCoord(int index, string[] args, out CoordF result)
    {
        float[] coord = new float[3];
        coord[0] = float.TryParse(args[index + 1], out float x) ? x : 0;
        coord[1] = float.TryParse(args[index + 2], out float y) ? y : 0;
        coord[2] = float.TryParse(args[index + 3], out float z) ? z : 0;
        result = CoordF.From(coord[0], coord[1], coord[2]);
    }

19 View Source File : GraphCLI.Parser.cs
License : MIT License
Project Creator : alelievr

static object TryParseGraphAttr(string s)
		{
			object value = null;
			int vi;
			long vl;
			float vf;
			double vd;
			bool vb;

			if (int.TryParse(s, out vi))
				value = vi;
			else if (long.TryParse(s, out vl))
				value = vl;
			else if (float.TryParse(s, out vf))
				value = vf;
			else if (double.TryParse(s, out vd))
				value = vd;
			else if (bool.TryParse(s, out vb))
				value = vb;
			
			return value;
		}

19 View Source File : CubeLutAssetImporter.cs
License : MIT License
Project Creator : alelievr

static void ImportCubeLut(string path)
        {
            // Remove the 'replacedets' part of the path & build absolute path
            string fullpath = path.Substring(7);
            fullpath = Path.Combine(Application.dataPath, fullpath);

            // Read the lut data
            string[] lines = File.ReadAllLines(fullpath);

            // Start parsing
            int i = 0;
            int size = -1;
            int sizeCube = -1;
            var table = new List<Color>();
            var domainMin = Color.black;
            var domainMax = Color.white;

            while (true)
            {
                if (i >= lines.Length)
                {
                    if (table.Count != sizeCube)
                        Debug.LogError("Premature end of file");

                    break;
                }

                string line = FilterLine(lines[i]);

                if (string.IsNullOrEmpty(line))
                    goto next;

                // Header data
                if (line.StartsWith("replacedLE"))
                    goto next; // Skip the replacedle tag, we don't need it

                if (line.StartsWith("LUT_3D_SIZE"))
                {
                    string sizeStr = line.Substring(11).TrimStart();

                    if (!int.TryParse(sizeStr, out size))
                    {
                        Debug.LogError("Invalid data on line " + i);
                        break;
                    }

                    if (size < 2 || size > 256)
                    {
                        Debug.LogError("LUT size out of range");
                        break;
                    }

                    sizeCube = size * size * size;
                    goto next;
                }

                if (line.StartsWith("DOMAIN_MIN"))
                {
                    if (!ParseDomain(i, line, ref domainMin)) break;
                    goto next;
                }

                if (line.StartsWith("DOMAIN_MAX"))
                {
                    if (!ParseDomain(i, line, ref domainMax)) break;
                    goto next;
                }

                // Table
                string[] row = line.Split();

                if (row.Length != 3)
                {
                    Debug.LogError("Invalid data on line " + i);
                    break;
                }

                var color = Color.black;
                for (int j = 0; j < 3; j++)
                {
                    float d;
                    if (!float.TryParse(row[j], out d))
                    {
                        Debug.LogError("Invalid data on line " + i);
                        break;
                    }

                    color[j] = d;
                }

                table.Add(color);

            next:
                i++;
            }

            if (sizeCube != table.Count)
            {
                Debug.LogError("Wrong table size - Expected " + sizeCube + " elements, got " + table.Count);
                return;
            }

            // Check if the Texture3D already exists, update it in this case (better workflow for
            // the user)
            string replacedetPath = Path.ChangeExtension(path, ".replacedet");
            var tex = replacedetDatabase.LoadreplacedetAtPath<Texture3D>(replacedetPath);

            if (tex != null)
            {
                tex.SetPixels(table.ToArray(), 0);
                tex.Apply();
            }
            else
            {
                // Generate a new Texture3D
                tex = new Texture3D(size, size, size, TextureFormat.RGBAHalf, false)
                {
                    anisoLevel = 0,
                    filterMode = FilterMode.Bilinear,
                    wrapMode = TextureWrapMode.Clamp,
                };

                tex.SetPixels(table.ToArray(), 0);
                tex.Apply();

                // Save to disk
                replacedetDatabase.Createreplacedet(tex, replacedetPath);
            }

            replacedetDatabase.Savereplacedets();
            replacedetDatabase.Refresh();
        }

19 View Source File : CubeLutAssetImporter.cs
License : MIT License
Project Creator : alelievr

static bool ParseDomain(int i, string line, ref Color domain)
        {
            string[] domainStrs = line.Substring(10).TrimStart().Split();

            if (domainStrs.Length != 3)
            {
                Debug.LogError("Invalid data on line " + i);
                return false;
            }

            for (int j = 0; j < 3; j++)
            {
                float d;
                if (!float.TryParse(domainStrs[j], out d))
                {
                    Debug.LogError("Invalid data on line " + i);
                    return false;
                }

                domain[j] = d;
            }

            return true;
        }

19 View Source File : ParameterForm.cs
License : MIT License
Project Creator : AlexGyver

private void dataGridView_CellValidating(object sender, 
      DataGridViewCellValidatingEventArgs e) 
    {
      float value;
      if (e.ColumnIndex == 2 &&
        !float.TryParse(e.FormattedValue.ToString(), out value)) {
        dataGridView.Rows[e.RowIndex].Cells[0].ErrorText = 
          "Invalid value";
        e.Cancel = true;
      }
    }

19 View Source File : VisualizationHeatmapCSV.cs
License : Apache License 2.0
Project Creator : allenai

void Start() {
        string[] data = CSVFile.text.Split(new char[] { '\n' });
        float x, z, r;

        for (int i = 1; i < data.Length - 1; i++) {
            string[] row = data[i].Split(new char[] { ',' });

            float.TryParse(row[0], out x);
            xvalues.Add(x);

            float.TryParse(row[1], out z);
            zvalues.Add(z);

            float.TryParse(row[2], out r);
            rotationvalues.Add(r);
        }

        for (int i = 0; i < xvalues.Count; i++) {
            Vector3 pos = new Vector3(xvalues[i], 1, zvalues[i]);
            Vector3 rot = new Vector3(0, rotationvalues[i], 0);

            // just spawn the Heavy prefab for now since it is the most visible
            Instantiate(prefabHeavy, pos, Quaternion.Euler(rot));
        }
    }

19 View Source File : ColorToBrushConv.cs
License : MIT License
Project Creator : amwx

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var color = (Color2)value;

			float amount;
			if (!float.TryParse(parameter.ToString(), out amount))
			{
				amount = 0;
			}

			return new SolidColorBrush(color.LightenPercent(amount));
		}

19 View Source File : PrinterStatus.cs
License : MIT License
Project Creator : andycb

private static Vector3 GetEndstopVector(string strVal)
        {
            // Example format: X-max:1 Y-max:0 Z-max:0
            var result = new Vector3(float.NaN);
            
            /// First break out each of the X/Y/Z planes
            var xyzParts = strVal.Split(' ');
            foreach (var plane in xyzParts)
            {
                // For each plane break into a key and value
                var planeParts = plane.Split(':');
                if (planeParts.Length == 2)
                {
                    // Attemt to parse the value
                    if (float.TryParse(planeParts[1], out var val))
                    {
                        // replacedign the parsed value to the relevent plane
                        switch(planeParts[0].ToLowerInvariant())
                        {
                            case "x-max":
                                result.X = val;
                                break;

                            case "y-max":
                                result.Y = val;
                                break;

                            case "z-max":
                                result.Z = val;
                                break;
                        }
                    }
                }
            }

            return result;
        }

19 View Source File : Keyboard.cs
License : GNU Lesser General Public License v3.0
Project Creator : angturil

bool ReadFloat(ref String data, ref int Position, ref float result)
        {
            if (Position >= data.Length) return false;
            int start = Position;
            while (Position < data.Length)
            {
                char c = data[Position];
                if (!((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')) break;
                Position++;
            }

            if (float.TryParse(data.Substring(start, Position - start), out result)) return true;

            Position = start;
            return false;
        }

19 View Source File : EgsDoseLoader.cs
License : Apache License 2.0
Project Creator : anmcgrath

private float ReadFloat(TextReader reader)
        {
            string numberString = readNumberString(reader);
            bool parseNumber = float.TryParse(numberString, out float number);
            if (parseNumber)
                return number;
            else
                return float.NaN;
        }

19 View Source File : NumericTextbox.cs
License : GNU General Public License v3.0
Project Creator : anotak

public float GetResultFloat(float original)
		{
			string textpart = this.Text;
			float result;

			// Strip prefixes
			textpart = textpart.Replace("+", "");
			textpart = textpart.Replace("-", "");

			// Any numbers left?
			if(textpart.Length > 0)
			{
				// Prefixed with ++?
				if(this.Text.StartsWith("++"))
				{
					// Add number to original
					if(!float.TryParse(textpart, out result)) result = 0;
					return original + result;
				}
				// Prefixed with --?
				else if(this.Text.StartsWith("--"))
				{
					// Subtract number from original
					if(!float.TryParse(textpart, out result)) result = 0;
					float newvalue = original - result;
					if(!allownegative && (newvalue < 0)) newvalue = 0;
					return newvalue;
				}
				else
				{
					// Return the new value
					return float.TryParse(this.Text, out result) ? result : original;
				}
			}
			else
			{
				// Nothing given, keep original value
				return original;
			}
		}

19 View Source File : NmsStreamMessage.cs
License : Apache License 2.0
Project Creator : apache

public float ReadSingle()
        {
            CheckWriteOnlyBody();
            CheckBytesInFlight();

            float result;
            object value = facade.Peek();
            if (value is float floatValue)
                result = floatValue;
            else if (value is string stringValue && float.TryParse(stringValue, out var parsedValue))
                result = parsedValue;
            else if (value is null)
                throw new NullReferenceException("Cannot convert null value to float.");
            else
                throw new MessageFormatException("stream value: " + value.GetType().Name + " cannot be converted to float.");

            facade.Pop();
            return result;
        }

19 View Source File : NmsStreamMessage.cs
License : Apache License 2.0
Project Creator : apache

public double ReadDouble()
        {
            CheckWriteOnlyBody();
            CheckBytesInFlight();

            double result;
            object value = facade.Peek();
            if (value is double doubleValue)
                result = doubleValue;
            else if (value is float floatValue)
                result = floatValue;
            else if (value is string stringValue && float.TryParse(stringValue, out var parsedValue))
                result = parsedValue;
            else if (value is null)
                throw new NullReferenceException("Cannot convert null value to long.");
            else
                throw new MessageFormatException("stream value: " + value.GetType().Name + " cannot be converted to double.");

            facade.Pop();
            return result;
        }

19 View Source File : DebugLogConsole.cs
License : MIT License
Project Creator : ArcturusZhang

private static bool ParseFloat( string input, out object output )
		{
			bool result;
			float value;
			result = float.TryParse( input, out value );

			output = value;
			return result;
		}

19 View Source File : DebugLogConsole.cs
License : MIT License
Project Creator : ArcturusZhang

private static bool CreateVectorFromInput( string input, Type vectorType, out object output )
		{
			List<string> tokens = new List<string>( input.Replace( ',', ' ' ).Trim().Split( ' ' ) );

			int i;
			for( i = tokens.Count - 1; i >= 0; i-- )
			{
				tokens[i] = tokens[i].Trim();
				if( tokens[i].Length == 0 )
					tokens.RemoveAt( i );
			}

			float[] tokenValues = new float[tokens.Count];
			for( i = 0; i < tokens.Count; i++ )
			{
				float val;
				if( !float.TryParse( tokens[i], out val ) )
				{
					if( vectorType == typeof( Vector3 ) )
						output = new Vector3();
					else if( vectorType == typeof( Vector2 ) )
						output = new Vector2();
					else
						output = new Vector4();

					return false;
				}

				tokenValues[i] = val;
			}

			if( vectorType == typeof( Vector3 ) )
			{
				Vector3 result = new Vector3();

				for( i = 0; i < tokenValues.Length && i < 3; i++ )
					result[i] = tokenValues[i];

				for( ; i < 3; i++ )
					result[i] = 0;

				output = result;
			}
			else if( vectorType == typeof( Vector2 ) )
			{
				Vector2 result = new Vector2();

				for( i = 0; i < tokenValues.Length && i < 2; i++ )
					result[i] = tokenValues[i];

				for( ; i < 2; i++ )
					result[i] = 0;

				output = result;
			}
			else
			{
				Vector4 result = new Vector4();

				for( i = 0; i < tokenValues.Length && i < 4; i++ )
					result[i] = tokenValues[i];

				for( ; i < 4; i++ )
					result[i] = 0;

				output = result;
			}

			return true;
		}

19 View Source File : DelayablePathfinderAction.cs
License : MIT License
Project Creator : Arkhist

public override void LoadFromXml(ElementInfo info)
        {
            base.LoadFromXml(info);
            
            if (Delay != null && !float.TryParse(Delay, out delay))
                throw new FormatException($"{this.GetType().Name}: Couldn't parse delay time!");
        }

19 View Source File : ElementInfo.cs
License : MIT License
Project Creator : Arkhist

public float ContentAsFloat()
            => float.TryParse(Content, out var value)
                ? value
                : throw new FormatException($"Value of '{Name}' is not a float, e.g.: 1.0");

See More Examples