System.Convert.ToDecimal(object)

Here are the examples of the csharp api System.Convert.ToDecimal(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

613 Examples 7

19 Source : JVMObject.cs
with MIT License
from CoFlows

public bool TrySetMember(string name, object value)
        {
            if(value is Delegate)
            {
                string signature = name;
                Delegate fun = value as Delegate;
                Members[signature] = fun;
                return true;
            }
            else
            {
                if (Properties.ContainsKey(name))
                {
                    Tuple<string, object, Runtime.wrapSetProperty> funcs = (Tuple<string, object, Runtime.wrapSetProperty>)Properties[name];
                    string ttype = funcs.Item1;

                    switch (ttype)
                    {
                        case "bool":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToBoolean(value));
                            break;

                        case "byte":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToByte(value));
                            break;
                        
                        case "char":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToChar(value));
                            break;

                        case "short":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToInt16(value));
                            break;
                        
                        case "int":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToInt32(value));
                            break;

                        case "long":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToInt64(value));
                            break;
                        
                        case "float":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToDecimal(value));
                            break;

                        case "double":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToDouble(value));
                            break;

                        case "string":
                            ((Runtime.wrapSetProperty)funcs.Item3)(Convert.ToString(value));
                            break;

                        case "object":
                            ((Runtime.wrapSetProperty)funcs.Item3)(value);
                            break;

                        case "array":
                            ((Runtime.wrapSetProperty)funcs.Item3)((object[])value);
                            break;

                        default:
                            ((Runtime.wrapSetProperty)funcs.Item3)(value);
                            break;
                    
                    }
                    return true;
            
                }
            }
            return false;   
        }

19 Source : ConvertObject.cs
with Apache License 2.0
from CoreUnion

public static object GetDataByType(object data1, Type itype, params object[] myparams)
        {
            object result = new object();
            try
            {
                if (itype == typeof(decimal))
                {
                    result = Convert.ToDecimal(data1);
                    if (myparams.Length > 0)
                    {
                        result = Convert.ToDecimal(Math.Round(Convert.ToDecimal(data1), Convert.ToInt32(myparams[0])));
                    }
                }
                else if (itype == typeof(double))
                {

                    if (myparams.Length > 0)
                    {
                        result = Convert.ToDouble(Math.Round(Convert.ToDouble(data1), Convert.ToInt32(myparams[0])));
                    }
                    else
                    {
                        result = double.Parse(Convert.ToDecimal(data1).ToString("0.00"));
                    }
                }
                else if (itype == typeof(Int32))
                {
                    result = Convert.ToInt32(data1);
                }
                else if (itype == typeof(DateTime))
                {
                    result = Convert.ToDateTime(data1);
                }
                else if (itype == typeof(Guid))
                {
                    result = new Guid(data1.ToString());
                }
                else if (itype == typeof(string))
                {
                    result = data1.ToString();
                }
            }
            catch
            {
                if (itype == typeof(decimal))
                {
                    result = 0;
                }
                else if (itype == typeof(double))
                {
                    result = 0;
                }
                else if (itype == typeof(Int32))
                {
                    result = 0;
                }
                else if (itype == typeof(DateTime))
                {
                    result = null;
                }
                else if (itype == typeof(Guid))
                {
                    result = Guid.Empty;
                }
                else if (itype == typeof(string))
                {
                    result = "";
                }
            }
            return result;
        }

19 Source : StringExtension.cs
with MIT License
from cq-panda

public static decimal GetDecimal(this object obj)
        {
            if (System.DBNull.Value.Equals(obj) || null == obj)
                return 0;

            try
            {
                return Convert.ToDecimal(obj);
            }
            catch
            {
                return 0;
            }
        }

19 Source : StringExtension.cs
with MIT License
from cq-panda

public static dynamic GetDynamic(this object obj)
        {
            if (System.DBNull.Value.Equals(obj) || null == obj)
                return null;

            try
            {
                string str = obj.ToString();
                if (str.IsNumber(25, 15)) return Convert.ToDecimal(obj);
                else return str;
            }
            catch
            {
                return string.Empty;
            }
        }

19 Source : BsonValue.cs
with Apache License 2.0
from cs-util-com

public virtual int CompareTo(BsonValue other, Collation collation)
        {
            // first, test if types are different
            if (this.Type != other.Type)
            {
                // if both values are number, convert them to Decimal (128 bits) to compare
                // it's the slowest way, but more secure
                if (this.IsNumber && other.IsNumber)
                {
                    return Convert.ToDecimal(this.RawValue).CompareTo(Convert.ToDecimal(other.RawValue));
                }
                // if not, order by sort type order
                else
                {
                    return this.Type.CompareTo(other.Type);
                }
            }

            // for both values with same data type just compare
            switch (this.Type)
            {
                case BsonType.Null:
                case BsonType.MinValue:
                case BsonType.MaxValue:
                    return 0;

                case BsonType.Int32: return this.AsInt32.CompareTo(other.AsInt32);
                case BsonType.Int64: return this.AsInt64.CompareTo(other.AsInt64);
                case BsonType.Double: return this.AsDouble.CompareTo(other.AsDouble);
                case BsonType.Decimal: return this.AsDecimal.CompareTo(other.AsDecimal);

                case BsonType.String: return collation.Compare(this.replacedtring, other.replacedtring);

                case BsonType.Doreplacedent: return this.AsDoreplacedent.CompareTo(other);
                case BsonType.Array: return this.AsArray.CompareTo(other);

                case BsonType.Binary: return this.AsBinary.BinaryCompareTo(other.AsBinary);
                case BsonType.ObjectId: return this.AsObjectId.CompareTo(other.AsObjectId);
                case BsonType.Guid: return this.AsGuid.CompareTo(other.AsGuid);

                case BsonType.Boolean: return this.AsBoolean.CompareTo(other.AsBoolean);
                case BsonType.DateTime:
                    var d0 = this.AsDateTime;
                    var d1 = other.AsDateTime;
                    if (d0.Kind != DateTimeKind.Utc) d0 = d0.ToUniversalTime();
                    if (d1.Kind != DateTimeKind.Utc) d1 = d1.ToUniversalTime();
                    return d0.CompareTo(d1);

                default: throw new NotImplementedException();
            }
        }

19 Source : BsonValue.cs
with GNU General Public License v3.0
from Cytoid

public virtual int CompareTo(BsonValue other, Collation collation)
        {
            // first, test if types are different
            if (this.Type != other.Type)
            {
                // if both values are number, convert them to Decimal (128 bits) to compare
                // it's the slowest way, but more secure
                if (this.IsNumber && other.IsNumber)
                {
                    return Convert.ToDecimal(this.RawValue).CompareTo(Convert.ToDecimal(other.RawValue));
                }
                // if not, order by sort type order
                else
                {
                    var result = this.Type.CompareTo(other.Type);
                    return result < 0 ? -1 : result > 0 ? +1 : 0;
                }
            }

            // for both values with same data type just compare
            switch (this.Type)
            {
                case BsonType.Null:
                case BsonType.MinValue:
                case BsonType.MaxValue:
                    return 0;

                case BsonType.Int32: return this.AsInt32.CompareTo(other.AsInt32);
                case BsonType.Int64: return this.AsInt64.CompareTo(other.AsInt64);
                case BsonType.Double: return this.AsDouble.CompareTo(other.AsDouble);
                case BsonType.Decimal: return this.AsDecimal.CompareTo(other.AsDecimal);

                case BsonType.String: return collation.Compare(this.replacedtring, other.replacedtring);

                case BsonType.Doreplacedent: return this.AsDoreplacedent.CompareTo(other);
                case BsonType.Array: return this.AsArray.CompareTo(other);

                case BsonType.Binary: return this.AsBinary.BinaryCompareTo(other.AsBinary);
                case BsonType.ObjectId: return this.AsObjectId.CompareTo(other.AsObjectId);
                case BsonType.Guid: return this.AsGuid.CompareTo(other.AsGuid);

                case BsonType.Boolean: return this.AsBoolean.CompareTo(other.AsBoolean);
                case BsonType.DateTime:
                    var d0 = this.AsDateTime;
                    var d1 = other.AsDateTime;
                    if (d0.Kind != DateTimeKind.Utc) d0 = d0.ToUniversalTime();
                    if (d1.Kind != DateTimeKind.Utc) d1 = d1.ToUniversalTime();
                    return d0.CompareTo(d1);

                default: throw new NotImplementedException();
            }
        }

19 Source : HttpParameterFormatter.cs
with MIT License
from DarkWanderer

internal static string Format(ClickHouseType type, object value)
        {
            switch (type)
            {
                case NothingType nt:
                    return NullValueString;
                case IntegerType it:
                case FloatType ft:
                    return Convert.ToString(value, CultureInfo.InvariantCulture);
                case DecimalType dt:
                    return Convert.ToDecimal(value).ToString(CultureInfo.InvariantCulture);

                case DateType dt when value is DateTimeOffset @do:
                    return @do.Date.ToString("yyyy-MM-dd");
                case DateType dt:
                    return Convert.ToDateTime(value).ToString("yyyy-MM-dd");

                case StringType st:
                case FixedStringType tt:
                case Enum8Type e8t:
                case Enum16Type e16t:
                case IPv4Type ip4:
                case IPv6Type ip6:
                case UuidType uuidType:
                    return value.ToString();

                case LowCardinalityType lt:
                    return Format(lt.UnderlyingType, value);

                case DateTimeType dtt when value is DateTime dt:
                    return dt.ToString("s", CultureInfo.InvariantCulture);

                case DateTimeType dtt when value is DateTimeOffset dto:
                    return dto.ToString("s", CultureInfo.InvariantCulture);

                case DateTime64Type dtt when value is DateTime dtv:
                    return $"{dtv:yyyy-MM-dd HH:mm:ss.fffffff}";

                case DateTime64Type dtt when value is DateTimeOffset dto:
                    return $"{dto:yyyy-MM-dd HH:mm:ss.fffffff}";

                case NullableType nt:
                    return value is null || value is DBNull ? NullValueString : $"{Format(nt.UnderlyingType, value)}";

                case ArrayType arrayType when value is IEnumerable enumerable:
                    return $"[{string.Join(",", enumerable.Cast<object>().Select(obj => InlineParameterFormatter.Format(arrayType.UnderlyingType, obj)))}]";

                case TupleType tupleType when value is ITuple tuple:
                    return $"({string.Join(",", tupleType.UnderlyingTypes.Select((x, i) => InlineParameterFormatter.Format(x, tuple[i])))})";

                case MapType mapType when value is IDictionary dict:
                    var strings = string.Join(",", dict.Keys.Cast<object>().Select(k => $"{InlineParameterFormatter.Format(mapType.KeyType, k)} : {InlineParameterFormatter.Format(mapType.ValueType, dict[k])}"));
                    return $"{{{string.Join(",", strings)}}}";

                default:
                    throw new Exception($"Cannot convert {value} to {type}");
            }
        }

19 Source : InlineParameterFormatter.cs
with MIT License
from DarkWanderer

private static string FormatDecimal(DecimalType type, object value)
        {
            if (!(value is decimal decimalValue))
                decimalValue = Convert.ToDecimal(value);
            return type switch
            {
                Decimal128Type decimal128Type => $"toDecimal128({decimalValue.ToString(CultureInfo.InvariantCulture)},{decimal128Type.Scale})",
                Decimal64Type decimal64Type => $"toDecimal64({decimalValue.ToString(CultureInfo.InvariantCulture)},{decimal64Type.Scale})",
                Decimal32Type decimal32Type => $"toDecimal32({decimalValue.ToString(CultureInfo.InvariantCulture)},{decimal32Type.Scale})",
                DecimalType _ => decimalValue.ToString(CultureInfo.InvariantCulture),
                _ => throw new NotSupportedException($"Cannot convert value {value} to decimal type")
            };

19 Source : BinaryStreamWriter.cs
with MIT License
from DarkWanderer

public void Write(DecimalType decimalType, object value)
        {
            try
            {
                decimal multipliedValue = Convert.ToDecimal(value) * decimalType.Exponent;
                switch (decimalType.Size)
                {
                    case 4:
                        writer.Write((int)multipliedValue);
                        break;
                    case 8:
                        writer.Write((long)multipliedValue);
                        break;
                    default:
                        WriteLargeDecimal(decimalType, multipliedValue);
                        break;
                }
            }
            catch (OverflowException)
            {
                throw new ArgumentOutOfRangeException("value", value, $"Value cannot be represented as {decimalType}");
            }
        }

19 Source : TypeMapper.cs
with MIT License
from DataObjects-NET

public override void BindULong(DbParameter parameter, object value)
    {
      parameter.DbType = DbType.Decimal;
      parameter.Value = value == null ? DBNull.Value : (object) Convert.ToDecimal(value);
    }

19 Source : DBFWriter.cs
with GNU General Public License v3.0
from DeepHydro

private void WriteRecord(BinaryWriter dataOutput, Object[] objectArray)
        {
            dataOutput.Write((byte) ' ');
            for (int j = 0; j < header.FieldArray.Length; j++)
            {
                /* iterate throught fields */

                switch (header.FieldArray[j].DataType)
                {
                    case NativeDbType.Char:
                        if (objectArray[j] != null && objectArray[j] != DBNull.Value)
                        {
                            String str_value = objectArray[j].ToString();
                            dataOutput.Write(
                                Utils.textPadding(str_value,
                                                  CharEncoding,
                                                  header.FieldArray[j].
                                                      FieldLength
                                    )
                                );
                        }
                        else
                        {
                            dataOutput.Write(
                                Utils.textPadding("",
                                                  CharEncoding,
                                                  header.FieldArray[j].
                                                      FieldLength
                                    )
                                );
                        }

                        break;

                    case NativeDbType.Date:
                        if (objectArray[j] != null && objectArray[j] != DBNull.Value)
                        {
                            DateTime tDate = (DateTime) objectArray[j];

                            dataOutput.Write(
                                CharEncoding.GetBytes(tDate.ToString("yyyyMMdd")));
                        }
                        else
                        {
                            dataOutput.Write(
                                Utils.FillArray(new byte[8], DBFFieldType.Space));
                        }

                        break;

                    case NativeDbType.Float:

                        if (objectArray[j] != null && objectArray[j] != DBNull.Value)
                        {
                            Double tDouble = Convert.ToDouble(objectArray[j]);
                            dataOutput.Write(
                                Utils.NumericFormating(
                                    tDouble,
                                    CharEncoding,
                                    header.FieldArray[j].FieldLength,
                                    header.FieldArray[j].DecimalCount
                                    )
                                );
                        }
                        else
                        {
                            dataOutput.Write(
                                Utils.textPadding(
                                    DBFFieldType.Unknown,
                                    CharEncoding,
                                    header.FieldArray[j].FieldLength,
                                    Utils.ALIGN_RIGHT
                                    )
                                );
                        }

                        break;

                    case NativeDbType.Numeric:

                        if (objectArray[j] != null && objectArray[j] != DBNull.Value)
                        {
                            Decimal tDecimal = Convert.ToDecimal(objectArray[j]);
                            dataOutput.Write(
                                Utils.NumericFormating(
                                    tDecimal,
                                    CharEncoding,
                                    header.FieldArray[j].FieldLength,
                                    header.FieldArray[j].DecimalCount
                                    )
                                );
                        }
                        else
                        {
                            dataOutput.Write(
                                Utils.textPadding(
                                    DBFFieldType.Unknown,
                                    CharEncoding,
                                    header.FieldArray[j].FieldLength,
                                    Utils.ALIGN_RIGHT
                                    )
                                );
                        }

                        break;
                    case NativeDbType.Logical:

                        if (objectArray[j] != null && objectArray[j] != DBNull.Value)
                        {
                            if ((bool) objectArray[j])
                            {
                                dataOutput.Write(DBFFieldType.True);
                            }
                            else
                            {
                                dataOutput.Write(DBFFieldType.False);
                            }
                        }
                        else
                        {
                            dataOutput.Write(DBFFieldType.UnknownByte);
                        }

                        break;

                    case NativeDbType.Memo:
                        if (objectArray[j] != null && objectArray[j] != DBNull.Value)
                        {
                            var tMemoValue = ((MemoValue) objectArray[j]);

                            tMemoValue.Write(this);

                            dataOutput.Write( Utils.NumericFormating(tMemoValue.Block,CharEncoding,10,0));
                        }else
                         {
                             dataOutput.Write(
                             Utils.textPadding("",
                                               CharEncoding,
                                               10
                                 )
                             );
                         }


                        break;

                    default:
                        throw new DBFException("Unknown field type "
                                               + header.FieldArray[j].DataType);
                }
            } /* iterating through the fields */
        }

19 Source : RollupFunctions.cs
with Microsoft Public License
from demianrasko

private decimal GetValue(object obj)
        {
            if (obj is Money)
            {
                return ((Money)obj).Value;
            }
            else if (obj is decimal || obj is int || obj is long || obj is short || obj is float || obj is double)
            { 
                return Convert.ToDecimal(obj);
            }
            return 0;
            //throw new Exception("Invalid field type provided.");
        }

19 Source : FileSizeFormatProvider.cs
with MIT License
from DevZest

private static string TryFormat(string format, object arg)
        {
            if (string.IsNullOrEmpty(format)) return null;
            if (!(format.StartsWith("KB", StringComparison.OrdinalIgnoreCase) ||
                format.StartsWith("MB", StringComparison.OrdinalIgnoreCase) ||
                format.StartsWith("GB", StringComparison.OrdinalIgnoreCase) ||
                format.StartsWith("FS", StringComparison.OrdinalIgnoreCase))) return null;
            //only on numeric types (FileInfo.Length is a long)
            if (!(arg is long || arg is decimal || arg is int)) return null;

            //try to convert to decimal
            decimal size;
            try
            {
                size = Convert.ToDecimal(arg);
            }
            catch (InvalidCastException)
            {
                size = 0;
            }
            //try to parse the decimal points
            int dps;
            if (format.Length > 2)
                int.TryParse(format.Substring(2), out dps);
            else
                int.TryParse(format, out dps);

            if (format.Length > 1)                //standardize
                format = format.Substring(0, 2).ToUpper(); //get first two chars

            const int KB = 1024;
            const int MB = KB * 1024;
            const int GB = MB * 1024;
            string suffix = "B";

            //if one of KB, MB or GB, divide, round and stringify
            switch (format)
            {
                case "KB":
                    size = size / KB;
                    suffix = "KB";
                    break;
                case "MB":
                    size = size / MB;
                    suffix = "MB";
                    break;
                case "GB":
                    size = size / GB;
                    suffix = "GB";
                    break;
                case "FS":
                    if (size >= GB)
                    {
                        size = size / GB;
                        suffix = "GB";
                    }
                    else if (size >= MB)
                    {
                        size = size / MB;
                        suffix = "MB";
                    }
                    else if (size >= KB)
                    {
                        size = size / KB;
                        suffix = "KB";
                    }
                    break;
            }
            return string.Format("{0:N" + dps + "} " + suffix, size);
        }

19 Source : ValueInterfaceFormatterConverter.cs
with MIT License
from Dogwei

public decimal ToDecimal(object value)
            => SystemConvert.ToDecimal(value);

19 Source : BaseDirectRW.cs
with MIT License
from Dogwei

public decimal ReadDecimal()
        {
            return Convert.ToDecimal(DirectRead());
        }

19 Source : DbDataReaderReader.cs
with MIT License
from Dogwei

public decimal ReadDecimal() => Convert.ToDecimal(DirectRead());

19 Source : BasicConvert.Overload.cs
with MIT License
from Dogwei

decimal IXConverter<object, decimal>.Convert(object value)
			=> Convert.ToDecimal(value);

19 Source : ObjectConverter.cs
with GNU Lesser General Public License v3.0
from DynamicHands

public static string ToSpecflowTableValue(AttributeMetadata metadata, object parsed)
        {
            switch(metadata.AttributeType)
            {
                case AttributeTypeCode.Double: 
                    return Convert.ToDouble(parsed).ToString(NumberFormatInfo.InvariantInfo);

                case AttributeTypeCode.Decimal:
                case AttributeTypeCode.Money:
                    return Convert.ToDecimal(parsed).ToString(NumberFormatInfo.InvariantInfo);

                case AttributeTypeCode.Integer:
                    return Convert.ToInt32(parsed).ToString(NumberFormatInfo.InvariantInfo);

                case AttributeTypeCode.DateTime:
                    return ToDateTimeString(metadata, (DateTime)parsed);

                default:
                    return parsed.ToString();
            }
        }

19 Source : SQLiteDataReader.cs
with Mozilla Public License 2.0
from ehsan2022002

public override decimal GetDecimal(int i)
        {
            return Convert.ToDecimal(((object[])rows[current_row])[i]);
        }

19 Source : Calculator.cs
with MIT License
from Elem8100

private static decimal Execute(List<Token> inst, EvalContext param)
        {
            var stack = new Stack<object>();
            object obj;
            decimal d1, d2;
            foreach (var token in inst)
            {
                switch (token.Type)
                {
                    case TokenType.Number: stack.Push(Convert.ToDecimal(token.Value)); break;
                    case TokenType.ID:
                        if (param.TryGetValue(token.Value, out obj))
                        {
                            stack.Push(obj);
                        }
                        else
                        {
                            throw new Exception("ID '" + token.Value + "' not found.");
                        }
                        break;
                    case TokenType.Operator:
                        if (token.Tag == Tag.Unary)
                        {
                            d1 = Convert.ToDecimal(stack.Pop());
                            switch (token.Value)
                            {
                                case "+": stack.Push(d1); break;
                                case "-": stack.Push(-d1); break;
                            }
                        }
                        else
                        {
                            d2 = Convert.ToDecimal(stack.Pop());
                            d1 = Convert.ToDecimal(stack.Pop());
                            switch (token.Value)
                            {
                                case "+": stack.Push(d1 + d2); break;
                                case "-": stack.Push(d1 - d2); break;
                                case "*": stack.Push(d1 * d2); break;
                                case "/": stack.Push(d1 / d2); break;
                            }
                        }
                        break;
                    case TokenType.Dot:
                        throw new NotSupportedException();
                    case TokenType.CallStart: stack.Push(TokenType.CallStart); break;
                    case TokenType.CallEnd:
                        var p = new Stack<object>();
                        while (!TokenType.CallStart.Equals(obj = stack.Pop()))
                        {
                            p.Push(obj);
                        }
                        obj = (stack.Pop() as Delegate).DynamicInvoke(p.ToArray());
                        stack.Push(obj);
                        break;
                }
            }
            return stack.Count <= 0 ? 0 : Convert.ToDecimal(stack.Pop());
        }

19 Source : SilverlightMarkup.cs
with Apache License 2.0
from Epi-Info

public string BuildInputParams(
            string chartType, 
            string chartreplacedle, 
            string independentreplacedle, 
            string dependentreplacedle, 
            string independentValueFormat,
            string dependentValueFormat,
            string interval,
            string intervalUnit,
            object startFrom,
            DataTable regressionTable)
        {
            StringBuilder chartLineSeries = new StringBuilder();

            string independentValueType = "";
            string dependentValueType = "";

            chartType = chartType.Replace("\"", "");
            chartreplacedle = chartreplacedle.Replace("\"", "");
            independentreplacedle = independentreplacedle.Replace("\"", "");
            dependentreplacedle = dependentreplacedle.Replace("\"", "");

            switch (chartType.ToUpperInvariant().Replace(" ", ""))
            {
                case SilverlightStatics.Area:
                    chartType = SilverlightStatics.Area;
                    break;

                case SilverlightStatics.Column:
                    chartType = SilverlightStatics.Bar;
                    break;

                case SilverlightStatics.Bubble:
                    chartType = SilverlightStatics.Bubble;
                    break;

                case SilverlightStatics.EpiCurve:
                    chartType = SilverlightStatics.Histogram;
                    break;

                case SilverlightStatics.Bar:
                    chartType = SilverlightStatics.RotatedBar;
                    break;

                case SilverlightStatics.Line:
                    chartType = SilverlightStatics.Line;
                    break;

                case SilverlightStatics.Pie:
                    chartType = SilverlightStatics.Pie;
                    break;

                case SilverlightStatics.Scatter:
                    chartType = SilverlightStatics.Scatter;
                    break;

                case SilverlightStatics.Stacked:
                    chartType = SilverlightStatics.Stacked;
                    break;

                case SilverlightStatics.TreeMap:
                    chartType = SilverlightStatics.TreeMap;
                    break;

                default:
                    chartType = SilverlightStatics.Bar;
                    break;
            }

            chartLineSeries.Append("chartLineSeries=");

            DataTable distinct = regressionTable.DefaultView.ToTable(true, "SeriesName");

            if (regressionTable.Rows.Count == 0)
            {
                return string.Empty;
            }

            foreach (DataRow row in distinct.Rows)
            {
                string seriesName = row["SeriesName"].ToString();
                string filter = string.Format("SeriesName = '{0}'", seriesName);

                DataRow[] regressionData = regressionTable.Select(filter);

                if (chartLineSeries.ToString().EndsWith("chartLineSeries=") == false)
                {
                    chartLineSeries.Append(SilverlightStatics.SeparateLineSeries);
                }

                chartLineSeries.Append("(");
                chartLineSeries.Append("LineSeriesreplacedle");
                chartLineSeries.Append(seriesName);
                chartLineSeries.Append("LineSeriesreplacedle");

                Type indepValueType = typeof(string);
                indepValueType = regressionData[0]["Predictor"].GetType();
                independentValueType = indepValueType.ToString();
                                     
                chartLineSeries.Append(SilverlightStatics.IndependentValueFormat);
                chartLineSeries.Append(independentValueFormat);
                chartLineSeries.Append(SilverlightStatics.IndependentValueFormat);

                chartLineSeries.Append(SilverlightStatics.DependentValueFormat);
                chartLineSeries.Append(dependentValueFormat);
                chartLineSeries.Append(SilverlightStatics.DependentValueFormat);

                chartLineSeries.Append(SilverlightStatics.LineSeriesDataString);

                foreach (DataRow regression in regressionData)
                {
                    if (regression["Predictor"] is DateTime)
                    {
                        string dateTimeString = ((DateTime)regression["Predictor"]).ToString(_dateTimeFormat);
                        chartLineSeries.Append(dateTimeString);
                    }
                    else
                    {
                        chartLineSeries.Append(regression["Predictor"].ToString());
                    }

                    chartLineSeries.Append(SilverlightStatics.SeparateIndDepValues);
                    chartLineSeries.Append(regression["Response"].ToString());
                    chartLineSeries.Append(SilverlightStatics.SeparateDataPoints);
                }

                if (chartLineSeries.ToString().EndsWith(SilverlightStatics.SeparateDataPoints))
                {
                    string series = chartLineSeries.ToString().Substring(0, chartLineSeries.Length - SilverlightStatics.SeparateDataPoints.Length);
                    chartLineSeries = new StringBuilder();
                    chartLineSeries.Append(series);
                }

                chartLineSeries.Append(SilverlightStatics.LineSeriesDataString);
            }

            if (chartType == SilverlightStatics.Scatter)
            {
                List<NumericDataValue> dataValues = new List<NumericDataValue>();
                NumericDataValue minValue = null;
                NumericDataValue maxValue = null;
                foreach (DataRow row in regressionTable.Rows)
                {
                    if (row["Response"].Equals(DBNull.Value) || row["Predictor"].Equals(DBNull.Value))
                    {
                        continue;
                    }
                    NumericDataValue currentValue = new NumericDataValue() { DependentValue = Convert.ToDecimal(row["Response"]), IndependentValue = Convert.ToDecimal(row["Predictor"]) };
                    dataValues.Add(currentValue);
                    if (minValue == null)
                    {
                        minValue = currentValue;
                    }
                    else
                    {
                        if (currentValue.IndependentValue < minValue.IndependentValue)
                        {
                            minValue = currentValue;
                        }
                    }
                    if (maxValue == null)
                    {
                        maxValue = currentValue;
                    }
                    else
                    {
                        if (currentValue.IndependentValue > maxValue.IndependentValue)
                        {
                            maxValue = currentValue;
                        }
                    }
                }

                StatisticsRepository.LinearRegression linearRegression = new StatisticsRepository.LinearRegression();
                Dictionary<string, string> inputVariableList = new Dictionary<string, string>();
                inputVariableList.Add("Response", "dependvar");
                inputVariableList.Add("intercept", "true");
                inputVariableList.Add("includemissing", "false");
                inputVariableList.Add("p", "0.95");
                inputVariableList.Add("Predictor", "unsorted");

                StatisticsRepository.LinearRegression.LinearRegressionResults regresResults = linearRegression.LinearRegression(inputVariableList, regressionTable);

                object[] result = new object[] { dataValues, regresResults, maxValue, minValue };

                decimal coefficient = Convert.ToDecimal(regresResults.variables[0].coefficient);
                decimal constant = Convert.ToDecimal(regresResults.variables[1].coefficient);

                NumericDataValue newMaxValue = new NumericDataValue();
                newMaxValue.IndependentValue = maxValue.IndependentValue + 1;
                newMaxValue.DependentValue = (coefficient * maxValue.IndependentValue) + constant;
                NumericDataValue newMinValue = new NumericDataValue();
                newMinValue.IndependentValue = minValue.IndependentValue - 1;
                newMinValue.DependentValue = (coefficient * minValue.IndependentValue) + constant;

                chartLineSeries.Append("LineSeriesDataString)^((LineSeriesreplacedleLinear RegressionLineSeriesreplacedleIndependentValueFormatIndependentValueFormatDependentValueFormatDependentValueFormatLineSeriesDataString");
                chartLineSeries.Append(newMinValue.IndependentValue.ToString());
                chartLineSeries.Append("^sidv^");
                chartLineSeries.Append(newMinValue.DependentValue.ToString());
                chartLineSeries.Append("^&^");
                chartLineSeries.Append(newMaxValue.IndependentValue.ToString());
                chartLineSeries.Append("^sidv^");
                chartLineSeries.Append(newMaxValue.DependentValue.ToString());
                chartLineSeries.Append("LineSeriesDataString");
            }

            chartLineSeries.Append(")");

            string inputParams = string.Empty;

            if (chartType.Length > 0) inputParams += string.Format("chartType={0},", chartType);
            if (chartreplacedle.Length > 0) inputParams += string.Format("chartreplacedle={0},", chartreplacedle);

            if (independentreplacedle.Length > 0) inputParams += string.Format("independentLabel={0},", independentreplacedle);
            if (dependentreplacedle.Length > 0) inputParams += string.Format("dependentLabel={0},", dependentreplacedle);

            if (independentValueFormat.Length > 0) inputParams += string.Format("independentValueFormat={0},", independentValueFormat);
            if (dependentValueFormat.Length > 0) inputParams += string.Format("dependentValueFormat={0},", dependentValueFormat);

            if (independentValueType.Length > 0) inputParams += string.Format("independentValueType={0},", independentValueType);
            if (dependentValueType.Length > 0) inputParams += string.Format("dependentValueType={0},", dependentValueType);

            if (interval.Length > 0) inputParams += string.Format("interval={0},", interval);
            if (intervalUnit.Length > 0) inputParams += string.Format("intervalUnit={0},", intervalUnit);

            if (startFrom is DateTime)
            {
                startFrom = ((DateTime)startFrom).ToString(_dateTimeFormat);
            }
            else
            {
                startFrom = startFrom.ToString();
            }
            
            
            if (((string)startFrom).Length > 0) inputParams += string.Format("startFrom={0},", ((string)startFrom));

            inputParams += chartLineSeries.Replace(",", SilverlightStatics.Comma);
            return inputParams;
        }

19 Source : GadgetStrataListPanel.xaml.cs
with Apache License 2.0
from Epi-Info

private void Redraw()
        {
            grdMain.Children.Clear();
            grdMain.RowDefinitions.Clear();
            grdMain.ColumnDefinitions.Clear();
            AddGridHeader();

            foreach (DataRowView rowView in dv)
            {
                DataRow row = rowView.Row;

                StrataGridListRow sRow = new StrataGridListRow();
                sRow.StrataLabel = row[0].ToString();
                if (row[1] == DBNull.Value)
                {
                    sRow.OutcomeRateExposure = null;
                }
                else
                {
                    sRow.OutcomeRateExposure = Convert.ToDecimal(row[1]);
                }

                if (row[2] == DBNull.Value)
                {
                    sRow.OutcomeRateNoExposure = null;
                }
                else
                {
                    sRow.OutcomeRateNoExposure = Convert.ToDecimal(row[2]);
                }                

                if (row[3] == DBNull.Value)
                {
                    sRow.RiskRatio = null;
                }
                else
                {
                    sRow.RiskRatio = Convert.ToDecimal(row[3]);
                }

                if (row[4] == DBNull.Value)
                {
                    sRow.OddsRatio = null;
                }
                else
                {
                    sRow.OddsRatio = Convert.ToDecimal(row[4]);
                }

                if (row[5] == DBNull.Value)
                {
                    sRow.OddsLower = null;
                }
                else
                {
                    sRow.OddsLower = Convert.ToDecimal(row[5]);
                }

                if (row[6] == DBNull.Value)
                {
                    sRow.OddsUpper = null;
                }
                else
                {
                    sRow.OddsUpper = Convert.ToDecimal(row[6]);
                }

                AddRow(sRow, false);
            }
        }

19 Source : GadgetStrataListPanel.xaml.cs
with Apache License 2.0
from Epi-Info

private void Redraw()
        {
            grdMain.Children.Clear();
            grdMain.RowDefinitions.Clear();
            grdMain.ColumnDefinitions.Clear();
            AddGridHeader();

            foreach (DataRowView rowView in dv)
            {
                DataRow row = rowView.Row;

                StrataGridListRow sRow = new StrataGridListRow();
                sRow.StrataLabel = row[0].ToString();
                if (row[1] == DBNull.Value)
                {
                    sRow.OutcomeRateExposure = null;
                }
                else
                {
                    sRow.OutcomeRateExposure = Convert.ToDecimal(row[1]);
                }

                if (row[2] == DBNull.Value)
                {
                    sRow.OutcomeRateNoExposure = null;
                }
                else
                {
                    sRow.OutcomeRateNoExposure = Convert.ToDecimal(row[2]);
                }                

                if (row[3] == DBNull.Value)
                {
                    sRow.RiskRatio = null;
                }
                else
                {
                    sRow.RiskRatio = Convert.ToDecimal(row[3]);
                }

                if (row[4] == DBNull.Value)
                {
                    sRow.RiskLower = null;
                }
                else
                {
                    sRow.RiskLower = Convert.ToDecimal(row[4]);
                }

                if (row[5] == DBNull.Value)
                {
                    sRow.RiskUpper = null;
                }
                else
                {
                    sRow.RiskUpper = Convert.ToDecimal(row[5]);
                }

                if (row[6] == DBNull.Value)
                {
                    sRow.OddsRatio = null;
                }
                else
                {
                    sRow.OddsRatio = Convert.ToDecimal(row[6]);
                }

                if (row[7] == DBNull.Value)
                {
                    sRow.OddsLower = null;
                }
                else
                {
                    sRow.OddsLower = Convert.ToDecimal(row[7]);
                }

                if (row[8] == DBNull.Value)
                {
                    sRow.OddsUpper = null;
                }
                else
                {
                    sRow.OddsUpper = Convert.ToDecimal(row[8]);
                }

                AddRow(sRow, false);
            }
        }

19 Source : BooleanToDecimalValueConverter.cs
with Apache License 2.0
from eXpandFramework

public override object ConvertToStorageType(object value) => value == null ? null : (object)Convert.ToDecimal(value);

19 Source : Base36Extensions.cs
with MIT License
from Facepunch

public static string ToBase36<T>( this T i ) where T : struct, IComparable, IComparable<T>, IConvertible, IEquatable<T>, IFormattable
        {
            var input = (long) Convert.ToDecimal( i );

            if ( input < 0 ) throw new ArgumentOutOfRangeException( "input", input, "input cannot be negative" );

            char[] clistarr = CharArray;
            var result = new Stack<char>();
            while ( input != 0 )
            {
                result.Push( clistarr[input % 36] );
                input /= 36;
            }

            return new string( result.ToArray() );
        }

19 Source : GeneralRecordWrapper.cs
with GNU General Public License v3.0
from faib920

public virtual decimal GetDecimal(IDataRecord reader, int i)
        {
            if (reader.IsDBNull(i))
            {
                return 0;
            }

            var type = reader.GetFieldType(i);
            if (type == typeof(decimal))
            {
                return reader.GetDecimal(i);
            }

            return Convert.ToDecimal(GetValue(reader, i));
        }

19 Source : EntityRowMapper.cs
with GNU General Public License v3.0
from faib920

private PropertyValue GetSupportedValue(bool isNull, PropertyMapping mapper, DataRow row)
        {
            if (mapper.Property.Type == typeof(Guid))
            {
                return isNull ? new Guid?() : new Guid(row[mapper.Index].ToString());
            }

            var typeCode = Type.GetTypeCode(mapper.Property.Type.GetNonNullableType());
            switch (typeCode)
            {
                case TypeCode.Boolean:
                    return isNull ? new bool?() : Convert.ToBoolean(row[mapper.Index]);
                case TypeCode.Char:
                    return isNull ? new char?() : Convert.ToChar(row[mapper.Index]);
                case TypeCode.Byte:
                    return isNull ? new byte?() : Convert.ToByte(row[mapper.Index]);
                case TypeCode.Int16:
                    return isNull ? new short?() : Convert.ToInt16(row[mapper.Index]);
                case TypeCode.Int32:
                    return isNull ? new int?() : Convert.ToInt32(row[mapper.Index]);
                case TypeCode.Int64:
                    return isNull ? new long?() : Convert.ToInt64(row[mapper.Index]);
                case TypeCode.Decimal:
                    return isNull ? new decimal?() : Convert.ToDecimal(row[mapper.Index]);
                case TypeCode.Double:
                    return isNull ? new double?() : Convert.ToDouble(row[mapper.Index]);
                case TypeCode.String:
                    return isNull ? string.Empty : Convert.ToString(row[mapper.Index]);
                case TypeCode.DateTime:
                    return isNull ? new DateTime?() : Convert.ToDateTime(row[mapper.Index]);
                case TypeCode.Single:
                    return isNull ? new float?() : Convert.ToSingle(row[mapper.Index]);
                default:
                    return PropertyValueHelper.NewValue(row[mapper.Index]);
            }
        }

19 Source : PropertyValueHelper.cs
with GNU General Public License v3.0
from faib920

internal static PropertyValue NewValue(object value, Type valueType)
        {
            Guard.ArgumentNull(valueType, "valueType");

            var nonNullType = valueType.GetNonNullableType();

            //如果是受支持的类型
            if (IsSupportedType(valueType))
            {
                //枚举
                if (nonNullType.IsEnum)
                {
                    return value == null && valueType.IsNullableType() ? null : (Enum)Enum.Parse(nonNullType, value.ToString());
                }
                //字节数组
                if (nonNullType.IsArray && valueType.GetElementType() == typeof(byte))
                {
                    return value == null ? new byte[0] : (byte[])value;
                }
                var isNull = value.IsNullOrEmpty();
                switch (nonNullType.FullName)
                {
                    case "System.Boolean": return isNull ? new bool?() : Convert.ToBoolean(value);
                    case "System.Byte": return isNull ? new byte?() : Convert.ToByte(value);
                    case "System.Char": return isNull ? new char?() : Convert.ToChar(value);
                    case "System.DateTime": return isNull ? new DateTime?() : Convert.ToDateTime(value);
                    case "System.Decimal": return isNull ? new decimal?() : Convert.ToDecimal(value);
                    case "System.Double": return isNull ? new double?() : Convert.ToDouble(value);
                    case "System.Guid": return isNull ? new Guid?() : new Guid(value.ToString());
                    case "System.Int16": return isNull ? new short?() : Convert.ToInt16(value);
                    case "System.Int32": return isNull ? new int?() : Convert.ToInt32(value);
                    case "System.Int64": return isNull ? new long?() : Convert.ToInt64(value);
                    case "System.Single": return isNull ? new float?() : Convert.ToSingle(value);
                    case "System.String": return isNull ? null : Convert.ToString(value);
                    case "System.Time": return isNull ? new TimeSpan?() : TimeSpan.Parse(value.ToString());
                    default: return null;
                }
            }
            return new PropertyValue(StorageType.Object) { Object = value };
        }

19 Source : TreeListNumericEditor.cs
with GNU General Public License v3.0
from faib920

public override void SetValue(object value)
        {
            ((NumericTextBox)Inner).Decimal = value == null ? 0 : Convert.ToDecimal(value);
        }

19 Source : TreeListNumericUpDownEditor.cs
with GNU General Public License v3.0
from faib920

public override void SetValue(object value)
        {
            var picker = (NumericUpDown)Inner;
            picker.Value = Convert.ToDecimal(value);
        }

19 Source : GeneralRecordWrapper.cs
with GNU Lesser General Public License v3.0
from faib920

public virtual decimal GetDecimal(IDataRecord reader, int i)
        {
            if (reader.IsDBNull(i))
            {
                return 0;
            }

            var type = reader.GetFieldType(i);
            if (type == typeof(decimal))
            {
                return reader.GetDecimal(i);
            }
            else if (type == typeof(byte))
            {
                return reader.GetByte(i);
            }
            else if (type == typeof(short))
            {
                return reader.GetInt16(i);
            }
            else if (type == typeof(int))
            {
                return reader.GetInt32(i);
            }
            else if (type == typeof(long))
            {
                return reader.GetInt64(i);
            }
            else if (type == typeof(float))
            {
                return Convert.ToDecimal(reader.GetFloat(i));
            }
            else if (type == typeof(double))
            {
                return Convert.ToDecimal(reader.GetDouble(i));
            }

            return Convert.ToDecimal(GetValue(reader, i));
        }

19 Source : EntityRowMapper.cs
with GNU Lesser General Public License v3.0
from faib920

private PropertyValue GetSupportedValue(bool isNull, PropertyMapping mapper, DataRow row)
        {
            if (mapper.Property.Type == typeof(Guid))
            {
                return isNull ? new Guid?() : new Guid(row[mapper.Index].ToString());
            }

            var typeCode = Type.GetTypeCode(mapper.Property.Type.GetNonNullableType());
            return typeCode switch
            {
                TypeCode.Boolean => isNull ? new bool?() : Convert.ToBoolean(row[mapper.Index]),
                TypeCode.Char => isNull ? new char?() : Convert.ToChar(row[mapper.Index]),
                TypeCode.Byte => isNull ? new byte?() : Convert.ToByte(row[mapper.Index]),
                TypeCode.Int16 => isNull ? new short?() : Convert.ToInt16(row[mapper.Index]),
                TypeCode.Int32 => isNull ? new int?() : Convert.ToInt32(row[mapper.Index]),
                TypeCode.Int64 => isNull ? new long?() : Convert.ToInt64(row[mapper.Index]),
                TypeCode.Decimal => isNull ? new decimal?() : Convert.ToDecimal(row[mapper.Index]),
                TypeCode.Double => isNull ? new double?() : Convert.ToDouble(row[mapper.Index]),
                TypeCode.String => isNull ? string.Empty : Convert.ToString(row[mapper.Index]),
                TypeCode.DateTime => isNull ? new DateTime?() : Convert.ToDateTime(row[mapper.Index]),
                TypeCode.Single => isNull ? new float?() : Convert.ToSingle(row[mapper.Index]),
                _ => PropertyValue.NewValue(row[mapper.Index], null),
            };

19 Source : Maper.cs
with GNU General Public License v3.0
from fiado07

private void SetMapedObject<TMapTo>(TMapTo newObject, IDataReader reader, Dictionary<string, string> dbtypes, System.Reflection.PropertyInfo propertyInfo) where TMapTo : new()
        {



            // check if column exists 
            bool columnExists = Enumerable.Range(0, reader.FieldCount).Any(i => reader.GetName(i) == propertyInfo.Name);

            // check 
            if (columnExists)
            {

                // -- Get values :: --
                var _result = Convert.IsDBNull(reader[propertyInfo.Name]) ? "" : reader[propertyInfo.Name];


                // get data type from db
                var dataTypes = dbtypes.FirstOrDefault(p => p.Key == propertyInfo.Name).Value.Trim();


                if (dataTypes.StartsWith("date"))
                {

                    // set data
                    propertyInfo.SetValue(newObject, Convert.ToDateTime(_result), null);

                }
                else if (dataTypes == "int")
                {
                    // set data
                    propertyInfo.SetValue(newObject, Convert.ToInt32(_result), null);

                }
                else if (dataTypes == "decimal")
                {
                    // set data
                    propertyInfo.SetValue(newObject, Convert.ToDecimal(_result), null);

                }
                else if (dataTypes == "Double")
                {
                    // set data
                    propertyInfo.SetValue(newObject, Convert.ToDouble(_result), null);
                }
                else
                {
                    // set data
                    propertyInfo.SetValue(newObject, _result.ToString().Trim(), null);

                }


            }


        }

19 Source : DbDataReaderExtensions.cs
with MIT License
from gordon-matt

public static decimal? GetDecimalNullable(this DbDataReader reader, int ordinal)
        {
            object value = reader.GetValue(ordinal);
            if (value == null || value == DBNull.Value)
            {
                return null;
            }

            return Convert.ToDecimal(value);
        }

19 Source : TraderClient.cs
with MIT License
from haardikk21

static void Main()
        {
            SuccessLog("binance-trader-csharp has been started");
            var config = JObject.Parse(System.IO.File.ReadAllText("config.json"));
            /* Binance Configuration */
            baseCurrency = (string)config["baseCurrency"];
            tradeCurrency = (string)config["tradeCurrency"];
            key = (string)config["key"];
            secret = (string)config["secret"];
            symbol = tradeCurrency + baseCurrency;
            InfoLog("Base Currency: " + baseCurrency + " | Trading Currency: " + tradeCurrency + " | Symbol: " + symbol);

            /* Bot Trade Configuration */
            tradeDifference = Convert.ToDecimal(config["tradeDifference"]);
            tradeProfit = Convert.ToDecimal(config["tradeProfit"]);
            tradeAmount = (int)config["tradeAmount"];
            InfoLog("Trade Difference: " + tradeDifference + " | Trade Profit: " + tradeProfit + "% | Trade Amount: " + tradeAmount);

            BinanceClient.SetDefaultOptions(new BinanceClientOptions()
            {
                ApiCredentials = new ApiCredentials(key, secret),
                LogVerbosity = LogVerbosity.None,
                LogWriter = null
            });

            var tick = new System.Timers.Timer();
            tick.Elapsed += Tick_Elapsed;
            tick.Interval = 3000;
            tick.Enabled = true;
            Console.ReadLine();
        }

19 Source : RDMPApplicationSettings.cs
with GNU General Public License v3.0
from HicServices

private bool AddOrUpdateValueInternal<T>(string key, T value, string fileName = null)
        {
            if (value == null)
            {
                Remove(key);

                return true;
            }

            var type = value.GetType();

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                type = type.GenericTypeArguments.FirstOrDefault();
            }


            if ((type == typeof(string)) ||
                (type == typeof(decimal)) ||
                (type == typeof(double)) ||
                (type == typeof(Single)) ||
                (type == typeof(DateTime)) ||
                (type == typeof(Guid)) ||
                (type == typeof(bool)) ||
                (type == typeof(Int32)) ||
                (type == typeof(Int64)) ||
                (type == typeof(byte)))
            {
                lock (locker)
                {
                    string str;

                    if (value is decimal)
                    {
                        return AddOrUpdateValue(key,
                            Convert.ToString(Convert.ToDecimal(value), System.Globalization.CultureInfo.InvariantCulture));
                    }
                    else if (value is DateTime)
                    {
                        return AddOrUpdateValue(key,
                            Convert.ToString(-(Convert.ToDateTime(value)).ToUniversalTime().Ticks,
                                System.Globalization.CultureInfo.InvariantCulture));
                    }
                    else
                        str = Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture);

                    string oldValue = null;

                    if (store.FileExists(key))
                    {
                        using (var stream = store.OpenFile(key, FileMode.Open))
                        {
                            using (var sr = new StreamReader(stream))
                            {
                                oldValue = sr.ReadToEnd();
                            }
                        }
                    }

                    using (var stream = store.OpenFile(key, FileMode.Create, FileAccess.Write))
                    {
                        using (var sw = new StreamWriter(stream))
                        {
                            sw.Write(str);
                        }
                    }

                    return oldValue != str;
                }
            }

            throw new ArgumentException(string.Format("Value of type {0} is not supported.", type.Name));
        }

19 Source : BsonValue.cs
with GNU General Public License v3.0
from hitchhiker

public virtual int CompareTo(BsonValue other)
        {
            // first, test if types are different
            if (this.Type != other.Type)
            {
                // if both values are number, convert them to Decimal (128 bits) to compare
                // it's the slowest way, but more secure
                if (this.IsNumber && other.IsNumber)
                {
                    return Convert.ToDecimal(this.RawValue).CompareTo(Convert.ToDecimal(other.RawValue));
                }
                // if not, order by sort type order
                else
                {
                    return this.Type.CompareTo(other.Type);
                }
            }

            // for both values with same data type just compare
            switch (this.Type)
            {
                case BsonType.Null:
                case BsonType.MinValue:
                case BsonType.MaxValue:
                    return 0;

                case BsonType.Int32: return ((Int32)this.RawValue).CompareTo((Int32)other.RawValue);
                case BsonType.Int64: return ((Int64)this.RawValue).CompareTo((Int64)other.RawValue);
                case BsonType.Double: return ((Double)this.RawValue).CompareTo((Double)other.RawValue);
                case BsonType.Decimal: return ((Decimal)this.RawValue).CompareTo((Decimal)other.RawValue);

                case BsonType.String: return string.Compare((String)this.RawValue, (String)other.RawValue);

                case BsonType.Doreplacedent: return this.AsDoreplacedent.CompareTo(other);
                case BsonType.Array: return this.AsArray.CompareTo(other);

                case BsonType.Binary: return ((Byte[])this.RawValue).BinaryCompareTo((Byte[])other.RawValue);
                case BsonType.ObjectId: return ((ObjectId)this.RawValue).CompareTo((ObjectId)other.RawValue);
                case BsonType.Guid: return ((Guid)this.RawValue).CompareTo((Guid)other.RawValue);

                case BsonType.Boolean: return ((Boolean)this.RawValue).CompareTo((Boolean)other.RawValue);
                case BsonType.DateTime:
                    var d0 = (DateTime)this.RawValue;
                    var d1 = (DateTime)other.RawValue;
                    if (d0.Kind != DateTimeKind.Utc) d0 = d0.ToUniversalTime();
                    if (d1.Kind != DateTimeKind.Utc) d1 = d1.ToUniversalTime();
                    return d0.CompareTo(d1);

                default: throw new NotImplementedException();
            }
        }

19 Source : Bit2CProvider.cs
with GNU General Public License v3.0
from hitchhiker

private Tuple<decimal, decimal> GetBidAskData(object[] data)
        {
            decimal price = Convert.ToDecimal(data[0]);
            decimal amount = Convert.ToDecimal(data[1]);

            return new Tuple<decimal, decimal>(price, amount);
        }

19 Source : QueryableDataReader.cs
with MIT License
from hoagsie

public override decimal GetDecimal(int ordinal)
        {
            return Convert.ToDecimal(this[ordinal]);
        }

19 Source : XmlTools.cs
with MIT License
from HotcakesCommerce

public static bool WriteSingleUpsPackage(ref XmlTextWriter xw, ref Package p)
        {
            var result = true;

            decimal dGirth = 0;

            decimal dLength = 0;
            decimal dHeight = 0;
            decimal dwidth = 0;

            var sar = new SortedList(2) {{1, p.Length}, {2, p.Width}, {3, p.Height}};

            var myEnumerator = sar.GetEnumerator();
            var place = 0;
            while (myEnumerator.MoveNext())
            {
                place += 1;
                switch (place)
                {
                    case 1:
                        dLength = Convert.ToDecimal(myEnumerator.Value);
                        break;
                    case 2:
                        dwidth = Convert.ToDecimal(myEnumerator.Value);
                        break;
                    case 3:
                        dHeight = Convert.ToDecimal(myEnumerator.Value);
                        break;
                }
            }
            myEnumerator = null;

            dGirth = dwidth + dwidth + dHeight + dHeight;
            
            //--------------------------------------------
            // Package
            xw.WriteStartElement("Package");

            xw.WriteStartElement("PackagingType");
            var packagingCode = Convert.ToInt32(p.Packaging).ToString();
            if (packagingCode.Length < 2)
            {
                packagingCode = "0" + packagingCode;
            }
            xw.WriteElementString("Code", packagingCode);
            if (p.Description != string.Empty)
            {
                xw.WriteElementString("Description", p.Description);
            }
            xw.WriteEndElement();

            if (p.Packaging == PackagingType.CustomerSupplied)
            {
                if (dLength > 0 | dHeight > 0 | dwidth > 0)
                {
                    xw.WriteStartElement("Dimensions");
                    xw.WriteStartElement("UnitOfMeasure");
                    switch (p.DimensionalUnits)
                    {
                        case UnitsType.Imperial:
                            xw.WriteElementString("Code", "IN");
                            break;
                        case UnitsType.Metric:
                            xw.WriteElementString("Code", "CM");
                            break;
                        default:
                            xw.WriteElementString("Code", "IN");
                            break;
                    }
                    xw.WriteEndElement();
                    xw.WriteElementString("Length", Math.Round(dLength, 0).ToString());
                    xw.WriteElementString("Width", Math.Round(dwidth, 0).ToString());
                    xw.WriteElementString("Height", Math.Round(dHeight, 0).ToString());
                    xw.WriteEndElement();
                }
            }

            // Weight
            if (p.Weight > 0)
            {
                xw.WriteStartElement("PackageWeight");
                xw.WriteStartElement("UnitOfMeasure");
                switch (p.WeightUnits)
                {
                    case UnitsType.Imperial:
                        xw.WriteElementString("Code", "LBS");
                        break;
                    case UnitsType.Metric:
                        xw.WriteElementString("Code", "KGS");
                        break;
                    default:
                        xw.WriteElementString("Code", "LBS");
                        break;
                }
                xw.WriteEndElement();
                xw.WriteElementString("Weight", Math.Round(p.Weight, 1).ToString());
                xw.WriteEndElement();
            }

            // Oversize Checks
            var oversizeCheck = dGirth + dLength;
            if (oversizeCheck > 84)
            {
                if (oversizeCheck < 108 & p.Weight < 30)
                {
                    xw.WriteElementString("OversizePackage", "1");
                }
                else
                {
                    if (p.Weight < 70)
                    {
                        xw.WriteElementString("OversizePackage", "2");
                    }
                    else
                    {
                        xw.WriteElementString("OversizePackage", "0");
                    }
                }
            }

            // ReferenceNumber
            if (p.ReferenceNumber != string.Empty)
            {
                xw.WriteStartElement("ReferenceNumber");
                var codeType = ConvertReferenceNumberCodeToString(p.ReferenceNumberType);
                xw.WriteElementString("Code", codeType);
                xw.WriteElementString("Value", TrimToLength(p.ReferenceNumber, 35));
                xw.WriteEndElement();
            }
            // ReferenceNumber2
            if (p.ReferenceNumber2 != string.Empty)
            {
                xw.WriteStartElement("ReferenceNumber");
                var codeType = ConvertReferenceNumberCodeToString(p.ReferenceNumber2Type);
                xw.WriteElementString("Code", codeType);
                xw.WriteElementString("Value", TrimToLength(p.ReferenceNumber2, 35));
                xw.WriteEndElement();
            }

            // Additional Handling
            if (p.AdditionalHandlingIsRequired)
            {
                xw.WriteElementString("AdditionalHandling", "");
            }

            //-------------------------------------------
            // Start Service Options
            xw.WriteStartElement("PackageServiceOptions");
            
            // Delivery Confirmation
            if (p.DeliveryConfirmation)
            {
                xw.WriteStartElement("DeliveryConfirmation");
                xw.WriteElementString("DCISType", Convert.ToInt32(p.DeliveryConfirmationType).ToString());
                if (p.DeliveryConfirmationControlNumber != string.Empty)
                {
                    xw.WriteElementString("DCISNumber", TrimToLength(p.DeliveryConfirmationControlNumber, 11));
                }
                xw.WriteEndElement();
            }

            // InsuredValue
            if (p.InsuredValue > 0)
            {
                xw.WriteStartElement("InsuredValue");
                xw.WriteElementString("MonetaryValue", p.InsuredValue.ToString());
                xw.WriteElementString("CurrencyCode", ConvertCurrencyCodeToString(p.InsuredValueCurrency));
                xw.WriteEndElement();
            }

            // COD
            if (p.COD)
            {
                xw.WriteStartElement("COD");
                xw.WriteElementString("CODCode", "3");
                xw.WriteElementString("CODFundsCode", Convert.ToInt32(p.CODPaymentType).ToString());
                xw.WriteStartElement("CODAmount");
                xw.WriteElementString("CurrencyCode", ConvertCurrencyCodeToString(p.CODCurrencyCode));
                xw.WriteElementString("MonetaryValue", p.CODAmount.ToString());
                xw.WriteEndElement();
                xw.WriteEndElement();
            }

            // Verbal Confirmation
            if (p.VerbalConfirmation)
            {
                xw.WriteStartElement("VerbalConfirmation");
                xw.WriteStartElement("ContactInfo");
                if (p.VerbalConfirmationName != string.Empty)
                {
                    xw.WriteElementString("Name", p.VerbalConfirmationName);
                }
                if (p.VerbalConfirmationPhoneNumber != string.Empty)
                {
                    xw.WriteElementString("PhoneNumber", p.VerbalConfirmationPhoneNumber);
                }
                xw.WriteEndElement();
                xw.WriteEndElement();
            }

            xw.WriteEndElement();
            // End Service Options
            //-------------------------------------------

            xw.WriteEndElement();
            // End Package
            //--------------------------------------------

            return result;
        }

19 Source : DeviceStateTests.cs
with MIT License
from i8beef

[Theory]
        [InlineData(GoogleType.Numeric, "1", 1, typeof(int))]
        [InlineData(GoogleType.Numeric, "2.5", 2.5, typeof(decimal))]
        [InlineData(GoogleType.Bool, "true", true, typeof(bool))]
        [InlineData(GoogleType.String, "true", "true", typeof(string))]
        [InlineData(GoogleType.Numeric, "SaladFork", default(int), typeof(int))]
        [InlineData(GoogleType.Bool, "SaladFork", default(bool), typeof(bool))]
        public void MapValueToGoogleConvertsTypes(GoogleType googleType, string value, object expected, Type expectedType)
        {
            // Arrange
            var deviceState = new DeviceState();

            // Hack for decimal constant values for InlineData
            if (expected is double)
            {
                expected = Convert.ToDecimal(expected);
            }

            // Act
            var result = deviceState.MapValueToGoogle(value, googleType);

            // replacedert
            replacedert.Equal(expected, result);
            replacedert.Equal(expectedType, result.GetType());
        }

19 Source : MainWindowViewModel.cs
with MIT License
from IUpdatable

private bool? WorksheetModel_OnBeforeChangeRecord(IRecordModel record, System.Reflection.PropertyInfo propertyInfo, object newProperyValue)
        {
            if (propertyInfo.Name.Equals("Price"))
            {
                decimal price = Convert.ToDecimal(newProperyValue);
                if (price > 100m) //replacedume the max price is 100
                {
                    MessageBox.Show("Max price is 100.", "Alert", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return true; // cancel the change
                }
            }

            return null;
        }

19 Source : ChloeMySqlDataReader.cs
with MIT License
from JackQChen

public decimal GetDecimal(int i)
        {
            object obj = this._reader.GetValue(i);
            if (obj is decimal)
                return (decimal)obj;

            return Convert.ToDecimal(obj);
        }

19 Source : OpenApiFluentValidationHelper.cs
with MIT License
from JamesRandall

public static decimal NumericToDecimal(this object value) => Convert.ToDecimal(value);

19 Source : Program.cs
with MIT License
from jinyuttt

static void Main(string[] args)
        {
            string str = "3e-6";
            var ss = Convert.ChangeType(str, typeof(float));
            Convert.ToDecimal(ss);
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(int));
            dt.Columns.Add("DTO", typeof(string));
            dt.Rows.Add(1, "3e-6");
            dt.Rows.Add(2, "5000");
            var lst = dt.ToEnreplacedyList<Person>();
            //foreach (DataRow row in dt.Rows)
            //{
            //    MyMethod(row);
            //}
        }

19 Source : Program.cs
with MIT License
from jinyuttt

public static Person MyMethod(DataRow P_0)
        {

            Person person = new Person();
            if (CanSetted(P_0, "Id"))
            {
                person.Id = Convert.ToInt32(P_0["Id"]);
            }
            if (CanSetted(P_0, "DTO"))
            {

                object obj = Convert.ToString(P_0["DTO"]);
                if (ScientificNotation(obj))
                {
                    obj = Convert.ToDouble(obj);
                }
                person.DTO = (Convert.ToDecimal(obj));
            }
            return person;
        }

19 Source : TestEmit.cs
with MIT License
from jinyuttt

public void  Test(DataRow row)
        {

            Person person = new Person();
            string str = Convert.ToString(row["DTO"]);
            object obj = str;
            if (string.IsNullOrEmpty(str))
            {
                 obj = Convert.ToDouble(str);
            }
            person.DTO = Convert.ToDecimal(obj);
          
            
         
        }

19 Source : UITypeEditorAngle.cs
with MIT License
from joergkrause

public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object val)
		{
            decimal value = Convert.ToDecimal(val);
			if (context != null && context.Instance != null && provider != null)
			{
				service = (IWindowsFormsEditorService) provider.GetService(typeof(IWindowsFormsEditorService));
				if (service != null)
				{
                    bool StartOver = true;
                    // look for a delegate attached by host app
                    if (UIEditorCallback != null)
                    {           
                        StartOver = false;
                        decimal oldVal = value;
                        DialogResult result = UIEditorCallback(context, ref value);
                        if (result != DialogResult.OK)
                        {
                            value = oldVal;
                            if (result == DialogResult.Ignore)
                            {
                                StartOver = true;
                            }
                        }
                    } 
                    if (StartOver)
                    {
                        AngleControl.BackColor = SystemColors.Control;
                        AngleControl.BorderStyle = BorderStyle.FixedSingle;
                        AngleControl.Angle = value;
                        AngleControl.Size = new Size(100, 100);
                        service.DropDownControl(AngleControl);
                        value = (decimal)AngleControl.Angle;
                    }
				}
			}
			return value;
		}

19 Source : ToggleButton.ascx.cs
with MIT License
from Kentico

private void HandleDecimalValue()
    {
        try
        {
            // Number of decimal digits could vary depending on field precision.
            var innerValueDecimal = Convert.ToDecimal(mInnerValue);
            var checkedValueDecimal = Convert.ToDecimal(CheckedValue);

            checkbox.Checked = checkedValueDecimal == innerValueDecimal;
        }
        catch (Exception e)
        {
            LogException(e);
        }
    }

19 Source : Single.cs
with MIT License
from kiler398

protected Decimal GetDecimal(DataColumn col)
		{
			if(null != col)
			{
				object o = _row[col];

				if(DBNull.Value != o)
					return Convert.ToDecimal(o);
			}

			return 0;
		}

See More Examples