double.ToString(string, System.IFormatProvider)

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

697 Examples 7

19 View Source File : FloatValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsNotBetween(float val, double start, double end, string key) =>
            IsNotBetween(val, (float)start, (float)end, key, FluntErrorMessages.IsNotBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : TimeSpanExtensions.cs
License : MIT License
Project Creator : AndreyAkinshin

public static string ToFormattedTotalTime(this TimeSpan time, CultureInfo cultureInfo)
        {
            long totalHours = time.Ticks / TimeSpan.TicksPerHour;
            string hhMmSs = $"{totalHours:00}:{time:mm\\:ss}";
            string totalSecs = $"{time.TotalSeconds.ToString("0.##", cultureInfo)} sec";
            return $"{hhMmSs} ({totalSecs})";
        }

19 View Source File : Toolbox.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal static string ValToString(object value, string stringFormat = "")
        {
            if (value == null) return "";
            if (value is string) return (string)value;
            if (value is bool) return ((bool)value).ToString(NumberFormatInfo.InvariantInfo);
            if (value is int) return ((int)value).ToString(stringFormat, NumberFormatInfo.InvariantInfo);
            if (value is float) return ((float)value).ToString(stringFormat, NumberFormatInfo.InvariantInfo);
            if (value is double) return ((double)value).ToString(stringFormat, NumberFormatInfo.InvariantInfo);
            return value.ToString();
        }

19 View Source File : DecimalValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsNotBetween(decimal val, double start, double end, string key) =>
            IsNotBetween(val, (decimal)start, (decimal)end, key, FluntErrorMessages.IsNotBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

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

public virtual string FormatValue(double x)
        {
            return x.ToString(ActualStringFormat, CultureInfo.InvariantCulture);
        }

19 View Source File : DoubleControlTemplate.cs
License : MIT License
Project Creator : Adoxio

protected override void InstantiateControlIn(Control container)
		{
			var textbox = new TextBox { ID = ControlID, TextMode = TextBoxMode.SingleLine, CssClreplaced = string.Join(" ", "text", CssClreplaced, Metadata.CssClreplaced), ToolTip = Metadata.ToolTip };
			textbox.Attributes["data-numberdecimalseparator"] = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

			if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
			{
				textbox.Attributes.Add("required", string.Empty);
			}

			if (Metadata.ReadOnly)
			{
				textbox.CssClreplaced += " readonly";
				textbox.Attributes["readonly"] = "readonly";
			}

			textbox.Attributes["onchange"] = "setIsDirty(this.id);";

			container.Controls.Add(textbox);

			RegisterClientSideDependencies(container);

			Bindings[Metadata.DataFieldName] = new CellBinding
			{
				Get = () =>
				{
					double value;

					return double.TryParse(textbox.Text, out value) ? new double?(value) : null;
				},
				Set = obj =>
				{
					var value = (double)obj;

					textbox.Text = value.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2)));
				}
			};
		}

19 View Source File : LongValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsNotBetween(long val, double start, double end, string key) =>
            IsNotBetween(val, (long)start, (long)end, key, FluntErrorMessages.IsNotBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

public string requestWithdrawal(CurrencyType currency, double amount)
        {
            if (amount <= 0)
                throw new BTCChinaException("requestWithdrawal", "N/A", "withdrawal amount cannot be negative nor zero");
            const string method = "requestWithdrawal";
            string mParams = "\"" + System.Enum.GetName(typeof(CurrencyType), currency) + "\"," + amount.ToString("F3", CultureInfo.InvariantCulture);
            return DoMethod(BuildParams(method, mParams));
        }

19 View Source File : Histogram.cs
License : MIT License
Project Creator : AndreyAkinshin

public override string ToString() => ToString(x => x.ToString("0.000", DateTimeFormatInfo.CurrentInfo));

19 View Source File : EvaluationResult.cs
License : MIT License
Project Creator : actions

public String ConvertToString()
        {
            switch (Kind)
            {
                case ValueKind.Null:
                    return String.Empty;

                case ValueKind.Boolean:
                    return ((Boolean)Value) ? ExpressionConstants.True : ExpressionConstants.False;

                case ValueKind.Number:
                    return ((Double)Value).ToString(ExpressionConstants.NumberFormat, CultureInfo.InvariantCulture);

                case ValueKind.String:
                    return Value as String;

                default:
                    return Kind.ToString();
            }
        }

19 View Source File : Formatter.cs
License : MIT License
Project Creator : andersnm

static void FormatNumber(double value, List<string> beforeDecimal, bool decimalSeparator, List<string> afterDecimal, bool thousandSeparator, CultureInfo culture, StringBuilder result)
        {
            int signitificantDigits = 0;
            if (afterDecimal != null)
                signitificantDigits = GetDigitCount(afterDecimal);

            var valueString = Math.Abs(value).ToString("F" + signitificantDigits, CultureInfo.InvariantCulture);
            var valueStrings = valueString.Split('.');
            var thousandsString = valueStrings[0];
            var decimalString = valueStrings.Length > 1 ? valueStrings[1].TrimEnd('0') : "";

            if (value < 0)
            {
                result.Append("-");
            }

            if (beforeDecimal != null)
            {
                FormatThousands(thousandsString, thousandSeparator, false, beforeDecimal, culture, result);
            }

            if (decimalSeparator) { 
                result.Append(culture.NumberFormat.NumberDecimalSeparator);
            }

            if (afterDecimal != null)
            {
                FormatDecimals(decimalString, afterDecimal, result);
            }
        }

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

private string GetAutoValue(double value, string auto)
        {
            if (double.IsNaN(value))
            {
                return auto;
            }

            return value.ToString(this.NumberFormat, CultureInfo.InvariantCulture);
        }

19 View Source File : TimeSpanExtensions.cs
License : Apache License 2.0
Project Creator : adamralph

public static string Humanize(this TimeSpan duration)
        {
            // less than one millisecond
            if (Convert.ToInt64(duration.TotalMilliseconds) < 1L)
            {
                return "<1 ms";
            }

            // milliseconds
            if (Convert.ToInt64(duration.TotalMilliseconds) < 1_000L)
            {
                return duration.TotalMilliseconds.ToString("F0", provider) + " ms";
            }

            // seconds
            if (Convert.ToInt64(duration.TotalSeconds * 100L) < 60_00L)
            {
                return duration.TotalSeconds.ToString("F2", provider) + " s";
            }

            // minutes and seconds
            if (Convert.ToInt64(duration.TotalSeconds) < 3600L)
            {
                var minutes = DivRem(Convert.ToInt64(duration.TotalSeconds), 60L, out var seconds);
                return seconds == 0
                    ? $"{minutes.ToString("F0", provider)} m"
                    : $"{minutes.ToString("F0", provider)} m {seconds.ToString("F0", provider)} s";
            }

            // minutes
            return duration.TotalMinutes.ToString("N0", provider) + " m";
        }

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsNotBetween(double val, double start, double end, string key) =>
            IsNotBetween(val, start, end, key, FluntErrorMessages.IsNotBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void ButtonApplyTLO_Click(object sender, RoutedEventArgs e)
		{
			if (machine.Mode != Machine.OperatingMode.Manual)
				return;

			double Z = (Properties.Settings.Default.TLSUseActualPos) ? machine.MachinePosition.Z : LastProbePosMachine.Z;

			double delta = Z - Properties.Settings.Default.ToolLengthSetterPos;

			machine.SendLine($"G43.1 Z{delta.ToString(Constants.DecimalOutputFormat)}");
		}

19 View Source File : IntValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsNotBetween(int val, double start, double end, string key) =>
            IsNotBetween(val, (int)start, (int)end, key, FluntErrorMessages.IsNotBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : RedisLiteHelper.cs
License : MIT License
Project Creator : AElfProject

public static byte[] ToFastUtf8Bytes(this double value)
        {
            return FastToUtf8Bytes(value.ToString("R", DoubleFormatProvider));
        }

19 View Source File : DoubleExtensions.cs
License : MIT License
Project Creator : AndreyAkinshin

public static string ToStringInvariant(this double value) => value.ToString(DefaultCultureInfo.Instance);

19 View Source File : Calculator.cs
License : MIT License
Project Creator : 3RD-Dimension

private string ExpressionEvaluator(string input)
		{
			try
			{
				Dictionary<string, double> variables = new Dictionary<string, double>();
				for (int i = 0; i < 3; i++)
				{
					variables.Add("M" + Axes[i], machine.MachinePosition[i]);
					variables.Add("W" + Axes[i], machine.WorkPosition[i]);
					variables.Add("PM" + Axes[i], machine.LastProbePosMachine[i]);
					variables.Add("PW" + Axes[i], machine.LastProbePosWork[i]);
				}

				variables.Add("TLO", machine.CurrentTLO);

				Expression expression = Expression.Parse(input);
				double value = expression.GetValue(variables);

				return value.ToString("0.###", Constants.DecimalOutputFormat);
			}
			catch (Exception ex)
			{
				Success = false;
				Console.WriteLine(ex.Message);
				return $"[{ex.Message}]";
			}
		}

19 View Source File : AdaptiveHistogramBuilder.cs
License : MIT License
Project Creator : AndreyAkinshin

public Histogram Build(IReadOnlyList<double> values, double binSize)
        {
            const double eps = 1e-9;
            const double margin = 0.1;
            const double adaptiveFactor = 0.02;

            if (binSize < eps)
                throw new ArgumentException(
                    $"binSize ({binSize.ToString("0.##", DefaultCultureInfo.Instance)}) should be a positive number",
                    nameof(binSize));
            if (binSize < Resolution)
                binSize = Resolution;
            binSize = NiceCeiling(binSize);

            var list = values.ToList();
            if (list.Count == 0)
                throw new ArgumentException("Values should be non-empty", nameof(values));

            list.Sort();
            if (list.Last() - list.First() < binSize)
            {
                double center = (list.First() + list.Last()) / 2;
                double lower = center - binSize / 2;
                double upper = center + binSize / 2;
                return new Histogram(binSize, new[] {new HistogramBin(lower, upper, list.ToArray())});
            }

            var points = new List<double> {NiceFloor(list.Min() - binSize / 2), NiceCeiling(list.Max() + binSize / 2)};
            int processedPointCount = 0;
            while (true)
            {
                if (points.Count > 10 * list.Count)
                {
                    var errorMessage = new StringBuilder();
                    errorMessage.AppendLine("Failed to run AdaptiveHistogramBuilder.BuildWithFixedBinSize");
                    errorMessage.AppendLine("BinSize: " + binSize.ToString("N12", DefaultCultureInfo.Instance));
                    errorMessage.AppendLine("Values: ");
                    foreach (double value in list)
                        errorMessage.AppendLine("  " + value.ToString("N12", DefaultCultureInfo.Instance));
                    throw new InvalidOperationException(errorMessage.ToString());
                }

                int pointIndex = -1;
                for (int i = processedPointCount; i < points.Count - 1; i++)
                {
                    double adaptiveBinSize = (points[i] + points[i + 1]) / 2.0 * adaptiveFactor;
                    double maxSize = Math.Max(binSize * (1.0 + 2 * margin), adaptiveBinSize);
                    if (points[i + 1] - points[i] > maxSize)
                    {
                        pointIndex = i;
                        break;
                    }
                }

                if (pointIndex == -1)
                    break;

                double lower = points[pointIndex];
                double upper = points[pointIndex + 1];

                int bestIndex1 = -1;
                int bestIndex2 = -1;
                int bestCount = -1;
                double bestDist = double.MaxValue;

                bool Inside(double x) => x > lower - eps && x < upper - eps;

                for (int i = 0; i < list.Count; i++)
                    if (Inside(list[i]))
                    {
                        int j = i;
                        while (j < list.Count && Inside(list[j]) && list[j] - list[i] < binSize)
                            j++;
                        int count = j - i;
                        double dist = list[j - 1] - list[i];
                        if (count > bestCount || count == bestCount && dist < bestDist)
                        {
                            bestCount = count;
                            bestIndex1 = i;
                            bestIndex2 = j - 1;
                            bestDist = dist;
                        }
                    }

                if (bestIndex1 != -1)
                {
                    double center = (list[bestIndex1] + list[bestIndex2]) / 2.0;
                    double adaptiveBinSize = Math.Max(binSize, center * adaptiveFactor);
                    double left = NiceFloor(center - adaptiveBinSize / 2);
                    double right = NiceFloor(Math.Min(center + adaptiveBinSize / 2, upper));

                    if (left > lower + binSize * margin)
                        points.Insert(pointIndex + 1, left);
                    else if (right < upper - binSize * margin && right > lower + binSize * margin)
                    {
                        points.Insert(pointIndex + 1, right);
                        processedPointCount++;
                    }
                    else
                        processedPointCount++;
                }
                else
                {
                    points.Insert(pointIndex + 1, NiceFloor(lower + binSize));
                    processedPointCount++;
                }
            }

            var bins = new List<HistogramBin>(points.Count - 1);
            int counter = 0;
            for (int i = 0; i < points.Count - 1; i++)
            {
                var bin = new List<double>();
                double lower = points[i];
                double upper = points[i + 1];

                while (counter < list.Count && (list[counter] < upper || i == points.Count - 1))
                    bin.Add(list[counter++]);

                bins.Add(new HistogramBin(lower, upper, bin.ToArray()));
            }

            // Trim
            while (bins.Any() && bins.First().IsEmpty)
                bins.RemoveAt(0);
            while (bins.Any() && bins.Last().IsEmpty)
                bins.RemoveAt(bins.Count - 1);

            // Join small bins to neighbors
            counter = 0;
            double lastValue = 0;
            while (counter < bins.Count)
            {
                if (bins[counter].HasAny)
                    lastValue = Math.Max(lastValue, bins[counter].Values.Last());
                double adaptiveThreshold = Math.Max(binSize / 3, lastValue * adaptiveFactor);
                if (bins[counter].Gap < adaptiveThreshold)
                {
                    double leftGap = counter > 0 ? bins[counter - 1].Gap : double.MaxValue;
                    double rightGap = counter < bins.Count - 1 ? bins[counter + 1].Gap : double.MaxValue;
                    if (leftGap < rightGap && counter > 0)
                    {
                        bins[counter - 1] = HistogramBin.Union(bins[counter - 1], bins[counter]);
                        bins.RemoveAt(counter);
                    }
                    else if (counter < bins.Count - 1)
                    {
                        bins[counter] = HistogramBin.Union(bins[counter], bins[counter + 1]);
                        bins.RemoveAt(counter + 1);
                    }
                    else
                        counter++;
                }
                else
                    counter++;
            }

            return new Histogram(binSize, bins.ToArray());
        }

19 View Source File : JsonConvert.cs
License : MIT License
Project Creator : akaskela

public static string ToString(double value)
        {
            return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
        }

19 View Source File : JsonConvert.cs
License : MIT License
Project Creator : akaskela

internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
        {
            return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
        }

19 View Source File : GrblSettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

public void LineReceived(string line)
        {
            // Recieve GRBL Controller Version number and display - $i
            // Recieved in format [VER: ... and [OPT:

            if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
                return;

            if (line.StartsWith("$"))
            {
                try
                {
                    Match m = settingParser.Match(line);
                    int number = int.Parse(m.Groups[1].Value);
                    double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);

                    // Value = Setting Value, Number = Setting Code

                    if (!CurrentSettings.ContainsKey(number))
                    {
                        RowDefinition rowDef = new RowDefinition();
                        rowDef.Height = new GridLength(25);
                        gridMain.RowDefinitions.Add(rowDef);

                        TextBox valBox = new TextBox // Value of Setting Textbox
                        {
                            Text = value.ToString(Util.Constants.DecimalOutputFormat),
                            VerticalAlignment = VerticalAlignment.Center
                        };

                        // Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
                        if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
                        else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
                        else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
                        Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
                        Grid.SetColumn(valBox, 1);
                        gridMain.Children.Add(valBox);

                        TextBlock num = new TextBlock
                        {
                            Text = $"${number}=",
                            HorizontalAlignment = HorizontalAlignment.Right,
                            VerticalAlignment = VerticalAlignment.Center
                        };
                        Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
                        Grid.SetColumn(num, 0);
                        gridMain.Children.Add(num);

                        if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
                        {
                            Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];

                            TextBlock name = new TextBlock
                            {
                                Text = labels.Item1,
                                VerticalAlignment = VerticalAlignment.Center
                            };
                            Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
                            Grid.SetColumn(name, 0);
                            gridMain.Children.Add(name);

                            TextBlock unit = new TextBlock
                            {
                                Text = labels.Item2,
                                VerticalAlignment = VerticalAlignment.Center
                            };
                            Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
                            Grid.SetColumn(unit, 2);
                            gridMain.Children.Add(unit);

                            valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
                        }

                        CurrentSettings.Add(number, value);
                        SettingsBoxes.Add(number, valBox);
                    }
                    else
                    {
                        SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
                        CurrentSettings[number] = value;
                    }
                }
                catch { }
            }
            // If the line starts with [VER: then we know we are getting the version and options
            else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
            {
                // Frist need to remove front [ and rear ]
                string VerOptInput; // Input string
                string[] VerOptTrimmed;
                VerOptInput = line.Remove(0, 1); // Remove [ from the start
                VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);

                // Next, split the values in half at the : - we only want VER/OPT and then the values
                VerOptTrimmed = VerOptInput.Split(':');

                // Now we fill in the boxes depending on which one
                switch (VerOptTrimmed[0])
                {
                    case "VER":
                        controllerInfo += "Version: " + VerOptTrimmed[1];
                        break;

                    case "OPT":
                        // First we have to split commas
                        string[] optSplit;
                        optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3.  0=Options, 1=blockBufferSize, 2=rxBufferSize
                        var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character

                        controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String

                        foreach (char c in individualChar)
                        {
                            // Lookup what each code is and display....  buildCodes Dictionary
                            if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
                            {
                                // Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
                                controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
                            }
                        }
                        controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
                        controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
                        GRBL_Controller_Info.Text = controllerInfo.ToString();
                        break;
                }
            }
        }

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

protected void WriteAttributeString(string name, double value)
        {
            this.WriteAttributeString(name, value.ToString(this.NumberFormat, CultureInfo.InvariantCulture));
        }

19 View Source File : NumberToken.cs
License : MIT License
Project Creator : actions

public override String ToString()
        {
            return m_value.ToString("G15", CultureInfo.InvariantCulture);
        }

19 View Source File : CompatibleConvert.cs
License : MIT License
Project Creator : andersnm

public static string ToString(object value, IFormatProvider provider)
        {
            switch (value)
            {
                case double d:
                    return d.ToString("G15", provider);
                case float f:
                    return f.ToString("G7", provider);
                default:
                    return Convert.ToString(value, provider);
            }
        }

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

private void AddContourLabels(
            Contour contour, ScreenPoint[] pts, OxyRect clippingRect, List<ContourLabel> contourLabels)
        {
            // todo: support label spacing and label step
            if (pts.Length < 2)
            {
                return;
            }

            // Calculate position and angle of the label
            double i = (pts.Length - 1) * 0.5;
            var i0 = (int)i;
            int i1 = i0 + 1;
            double dx = pts[i1].X - pts[i0].X;
            double dy = pts[i1].Y - pts[i0].Y;
            double x = pts[i0].X + (dx * (i - i0));
            double y = pts[i0].Y + (dy * (i - i0));
            if (!clippingRect.Contains(x, y))
            {
                return;
            }

            var pos = new ScreenPoint(x, y);
            double angle = Math.Atan2(dy, dx) * 180 / Math.PI;
            if (angle > 90)
            {
                angle -= 180;
            }

            if (angle < -90)
            {
                angle += 180;
            }

            string text = contour.ContourLevel.ToString(this.LabelFormatString, this.ActualCulture);
            contourLabels.Add(new ContourLabel { Position = pos, Angle = angle, Text = text });
        }

19 View Source File : VssApiResourceVersion.cs
License : MIT License
Project Creator : actions

private void FromVersionString(String apiVersionString)
        {
            if (String.IsNullOrEmpty(apiVersionString))
            {
                throw new VssInvalidApiResourceVersionException(apiVersionString);
            }

            // Check for a stage/resourceVersion string
            int dashIndex = apiVersionString.IndexOf('-');
            if (dashIndex >= 0)
            {
                String stageName;

                // Check for a '.' which separate stage from resource version
                int dotIndex = apiVersionString.IndexOf('.', dashIndex);
                if (dotIndex > 0)
                {
                    stageName = apiVersionString.Substring(dashIndex + 1, dotIndex - dashIndex - 1);

                    int resourceVersion;
                    String resourceVersionString = apiVersionString.Substring(dotIndex + 1);
                    if (!int.TryParse(resourceVersionString, out resourceVersion))
                    {
                        throw new VssInvalidApiResourceVersionException(apiVersionString);
                    }
                    else
                    {
                        this.ResourceVersion = resourceVersion;
                    }
                }
                else
                {
                    stageName = apiVersionString.Substring(dashIndex + 1);
                }

                // Check for supported stage names
                if (String.Equals(stageName, c_PreviewStageName, StringComparison.OrdinalIgnoreCase))
                {
                    IsPreview = true;
                }
                else
                {
                    throw new VssInvalidApiResourceVersionException(apiVersionString);
                }

                // Api version is the string before the dash
                apiVersionString = apiVersionString.Substring(0, dashIndex);
            }

            // Trim a leading "v" for version
            apiVersionString = apiVersionString.TrimStart('v');

            double apiVersionValue;
            if (!double.TryParse(apiVersionString, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out apiVersionValue))
            {
                throw new VssInvalidApiResourceVersionException(apiVersionString);
            }

            // Store the api version
            this.ApiVersion = new Version(apiVersionValue.ToString("0.0", CultureInfo.InvariantCulture));
        }

19 View Source File : DecimalValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsBetween(decimal val, double start, double end, string key) =>
            IsBetween(val, (decimal)start, (decimal)end, key, FluntErrorMessages.IsBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : GrblSettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private void ButtonGrblExport_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("This will export the currently displayed settings to a file - even any modified values that you have entered.  If you need to export the settings before modifications, please export before changing.  Continue To Export?", "Important", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            { // YES - Export               
                SaveFileDialog exportFileName = new SaveFileDialog();
                exportFileName.Filter = "Text File (*.txt)|*.txt";
                exportFileName.replacedle = "Save exported GRBL Settings";
                exportFileName.FileName = "Exported_GRBL_Settings.txt";

                if (exportFileName.ShowDialog() == true)
                {
                    List<Tuple<int, double>> ToExport = new List<Tuple<int, double>>();
                    foreach (KeyValuePair<int, double> kvp in CurrentSettings)
                    {
                        ToExport.Add(new Tuple<int, double>(kvp.Key, kvp.Value));
                    }

                    using (StreamWriter sw = new StreamWriter(exportFileName.FileName))
                    {
                        sw.WriteLine("{0,-10} {1,-10} {2,-18} {3, -35}", "Setting", "Value", "Units", "Description");

                        foreach (Tuple<int, double> setting in ToExport)
                        // setting.Item1 = GRBL Code, setting.Item2 = Setting Value, Util.GrblCodeTranslator.Settings[setting.Item1].Item1 = Setting Description, Util.GrblCodeTranslator.Settings[setting.Item1].Item2 = Units
                        {
                            sw.WriteLine("{0,-10} {1,-10} {2,-18} {3, -35}", "$" + setting.Item1, setting.Item2.ToString(Util.Constants.DecimalOutputFormat), Util.GrblCodeTranslator.Settings[setting.Item1].Item2, Util.GrblCodeTranslator.Settings[setting.Item1].Item1);
                        }
                        MessageBox.Show("Settings Exported to " + exportFileName.FileName, "Exported GRBL Settings", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            else
            { // NO
                return;
            }
        }

19 View Source File : DoubleValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsBetween(double val, double start, double end, string key) =>
            IsBetween(val, start, end, key, FluntErrorMessages.IsBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : CrmChartBuilder.cs
License : MIT License
Project Creator : Adoxio

private List<Dictionary<string, object>> ConvertRecordsToDictionary(OrganizationServiceContext serviceContext, IEnumerable<Enreplacedy> records, EnreplacedyMetadata enreplacedyMetadata)
		{
			var data = new List<Dictionary<string, object>>();
			var organizationMoneyFormatInfo = new OrganizationMoneyFormatInfo(serviceContext);

			foreach (var record in records)
			{
				var row = new Dictionary<string, object>
				{
					{ "RowId", record.Id.ToString("B", CultureInfo.InvariantCulture).ToUpper(CultureInfo.InvariantCulture) },
					{ "RowType", enreplacedyMetadata.ObjectTypeCode.GetValueOrDefault(0).ToString() }
				};

				// DateGrouping require us to also retrieve a datetime value so we can format series labels correctly. Grouping by day for example with a date like 9/23/2016 will result in the value 23 to be stored in the data. The DataDefinition is manually revised to add this aggregate attribute into the fetch so we get the actual date value 9/23/2016 displayed in the chart series.
				KeyValuePair<string, object> groupbyAttribute = new KeyValuePair<string, object>();
				object dategroupValue = null;
				var dategroupAttribute = record.Attributes.FirstOrDefault(a => a.Key.EndsWith("_dategroup_value"));
				if (!string.IsNullOrEmpty(dategroupAttribute.Key))
				{
					var aliasedDateGroupValue = dategroupAttribute.Value as AliasedValue;
					dategroupValue = aliasedDateGroupValue == null ? dategroupAttribute.Value : aliasedDateGroupValue.Value;
					groupbyAttribute = record.Attributes.FirstOrDefault(a =>
						a.Key != dategroupAttribute.Key
						&&
						a.Key.StartsWith(dategroupAttribute.Key.Substring(0, dategroupAttribute.Key.IndexOf("_dategroup_value", StringComparison.InvariantCulture))));
				}

				foreach (var attribute in record.Attributes)
				{
					var aliasedValue = attribute.Value as AliasedValue;
					var value = aliasedValue != null ? aliasedValue.Value : attribute.Value;
					var formattedValue = string.Empty;
					var attributeLogicalName = aliasedValue != null ? aliasedValue.AttributeLogicalName : attribute.Key;
					var attributeEnreplacedyLogicalName = aliasedValue != null ? aliasedValue.EnreplacedyLogicalName : enreplacedyMetadata.LogicalName;
					var attributeMetadata = this.GetAttributeMetadata(attributeLogicalName, attributeEnreplacedyLogicalName);
					
					if (record.FormattedValues.Contains(attribute.Key))
					{
						formattedValue = record.FormattedValues[attribute.Key];
					}

					if (attributeMetadata != null && value != null)
					{
						switch (attributeMetadata.AttributeType)
						{
							case AttributeTypeCode.Customer:
							case AttributeTypeCode.Lookup:
							case AttributeTypeCode.Owner:
								var enreplacedyReference = value as EnreplacedyReference;
								if (enreplacedyReference != null)
								{
									formattedValue = enreplacedyReference.Name;
								}
								break;
							case AttributeTypeCode.State:
							case AttributeTypeCode.Status:
							case AttributeTypeCode.Picklist:
								var optionSetValue = value as OptionSetValue;
								if (optionSetValue != null)
								{
									formattedValue =
										Adxstudio.Xrm.Core.OrganizationServiceContextExtensions.GetOptionSetValueLabel(attributeMetadata,
											optionSetValue.Value, this.contextLanguage.IsCrmMultiLanguageEnabled ? this.contextLanguage.ContextLanguage.CrmLcid : this.culture.LCID);
								}
								break;
							case AttributeTypeCode.Money:
								var money = value as Money;
								if (money != null)
								{
									value = money.Value;
									var moneyFormatter = new BaseCurrencyMoneyFormatter(organizationMoneyFormatInfo, CultureInfo.CurrentCulture);
									formattedValue = string.Format(moneyFormatter, "{0}", money);
								}
								break;
							case AttributeTypeCode.DateTime:
								if (!string.IsNullOrEmpty(dategroupAttribute.Key) && attribute.Key == groupbyAttribute.Key && dategroupValue != null)
								{
									value = dategroupValue;
								}
								if (value is DateTime)
								{
									formattedValue = ((DateTime)value).ToString(this.culture.DateTimeFormat.ShortDatePattern);
								}
								break;
							case AttributeTypeCode.BigInt:
							case AttributeTypeCode.Integer:
								if (value is int)
								{
									formattedValue = ((int)value).ToString("N", this.culture);
								}
								break;
							case AttributeTypeCode.Decimal:
								var decimalAttributeMetadata = attributeMetadata as DecimalAttributeMetadata;
								if (decimalAttributeMetadata != null && value is decimal)
								{
									formattedValue =
										((decimal)value).ToString(string.Format("N{0}", decimalAttributeMetadata.Precision.GetValueOrDefault(2)),
											this.culture);
								}
								break;
							case AttributeTypeCode.Double:
								var doubleAttributeMetadata = attributeMetadata as DoubleAttributeMetadata;
								if (doubleAttributeMetadata != null && value is double)
								{
									formattedValue =
										((double)value).ToString(string.Format("N{0}", doubleAttributeMetadata.Precision.GetValueOrDefault(2)),
											this.culture);
								}
								break;
						}
					}

					if (string.IsNullOrWhiteSpace(formattedValue))
					{
						try
						{
							formattedValue = value.ToString();
						}
						catch
						{
							// ignored
						}
					}

					if (!string.IsNullOrEmpty(formattedValue))
					{
						formattedValue = formattedValue.Replace("<", "<").Replace(">", ">");
					}

					row.Add(attribute.Key, formattedValue);
					row.Add(string.Format("{0}_Value", attribute.Key), value);
				}

				data.Add(row);
			}

			return data;
		}

19 View Source File : FloatValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsBetween(float val, double start, double end, string key) =>
            IsBetween(val, (float)start, (float)end, key, FluntErrorMessages.IsBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : TableColumnsTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public void TestNullableDouble()
        {
            replacedert.AreEqual(SqQueryBuilder.SqlType.Double, this.Table.ColNullableDouble.SqlType);
            replacedert.AreEqual("[AT].[ColNullableDouble]", this.Table.ColNullableDouble.ToSql());
            replacedert.IsTrue(this.Table.ColNullableDouble.IsNullable);

            DerivedTable dt = new DerivedTable();
            var customColumn = this.Table.ColNullableDouble.AddToDerivedTable(dt);
            replacedert.AreEqual(this.Table.ColNullableDouble.ColumnName, customColumn.ColumnName);
            replacedert.IsTrue(dt.Columns.Contains(customColumn));

            var customColumn2 = this.Table.ColNullableDouble.ToCustomColumn(this.NewSource);
            replacedert.AreEqual(this.Table.ColNullableDouble.ColumnName, customColumn2.ColumnName);

            var reader = new Mock<ISqDataRecordReader>();

            this.Table.ColNullableDouble.Read(reader.Object);
            customColumn.Read(reader.Object);

            reader.Verify(r => r.GetNullableDouble(It.Is<string>(name => name == customColumn.ColumnName.Name)), Times.Exactly(2));

            replacedert.IsNull(this.Table.ColNullableDouble.Readreplacedtring(reader.Object));
            reader.Setup(r => r.GetNullableDouble(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(-12.34567);
            replacedert.AreEqual((-12.34567).ToString("F", CultureInfo.InvariantCulture), this.Table.ColNullableDouble.Readreplacedtring(reader.Object));

            replacedert.AreEqual(12.34567.ToString("F", CultureInfo.InvariantCulture), this.Table.ColNullableDouble.FromString(12.34567.ToString("F", CultureInfo.InvariantCulture)).ToSql());
            replacedert.AreEqual("NULL", this.Table.ColNullableDouble.FromString(null).ToSql());
        }

19 View Source File : IntValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsBetween(int val, double start, double end, string key) =>
            IsBetween(val, (int)start, (int)end, key, FluntErrorMessages.IsBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : DoubleControlTemplate.cs
License : MIT License
Project Creator : Adoxio

protected override void InstantiateValidatorsIn(Control container)
		{
			var floatValidator = new CustomValidator
			{
				ID = string.Format("FloatValidator{0}", ControlID),
				ControlToValidate = ControlID,
				ValidationGroup = ValidationGroup,
				ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.ValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("float")) ? ResourceManager.GetString("Invalid_Floating_Point_Value_Error").FormatWith(Metadata.Label) : Metadata.Messages["float"].FormatWith(Metadata.Label) : Metadata.ValidationErrorMessage)),
				Text = "*",
			};

			floatValidator.ServerValidate += OnDoubleFormatValidate;

			container.Controls.Add(floatValidator);

			var maxValue = Metadata.MaxValue.HasValue ? Convert.ToDouble(Metadata.MaxValue.Value) : double.MaxValue;
			var minValue = Metadata.MinValue.HasValue ? Convert.ToDouble(Metadata.MinValue.Value) : double.MinValue;

			var rangeValidator = new CustomValidator
			{
				ID = string.Format("RangeValidator{0}", ControlID),
				ControlToValidate = ControlID,
				ValidationGroup = ValidationGroup,
				ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RangeValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("range")) ? ResourceManager.GetString("Invalid_Range_Error").FormatWith(Metadata.Label, minValue.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2))), maxValue.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2)))) : Metadata.Messages["range"].FormatWith(Metadata.Label, minValue.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2))), maxValue.ToString("N{0}".FormatWith(Metadata.Precision.GetValueOrDefault(2)))) : Metadata.RangeValidationErrorMessage)),
				Text = "*",
			};

			rangeValidator.ServerValidate += GetRangeValidationHandler(minValue, maxValue);

			container.Controls.Add(rangeValidator);

			if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired)
			{
				container.Controls.Add(new RequiredFieldValidator
				{
					ID = string.Format("RequiredFieldValidator{0}", ControlID),
					ControlToValidate = ControlID,
					ValidationGroup = ValidationGroup,
					Display = ValidatorDisplay,
					ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("required")) ? ResourceManager.GetString("Required_Field_Error").FormatWith(Metadata.Label) : Metadata.Messages["required"].FormatWith(Metadata.Label) : Metadata.RequiredFieldValidationErrorMessage)),
					Text = ValidationText,
				});
			}

			if (!string.IsNullOrWhiteSpace(Metadata.ValidationRegularExpression))
			{
				container.Controls.Add(new RegularExpressionValidator
				{
					ID = string.Format("RegularExpressionValidator{0}", ControlID),
					ControlToValidate = ControlID,
					ValidationGroup = ValidationGroup,
					ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.ValidationRegularExpressionErrorMessage) ? ResourceManager.GetString("Invalid_Error").FormatWith(Metadata.Label) : Metadata.ValidationRegularExpressionErrorMessage)),
					Text = "*",
					ValidationExpression = Metadata.ValidationRegularExpression
				});
			}

			this.InstantiateCustomValidatorsIn(container);
		}

19 View Source File : LongValidationContract.cs
License : MIT License
Project Creator : andrebaltieri

public Contract<T> IsBetween(long val, double start, double end, string key) =>
            IsBetween(val, (long)start, (long)end, key, FluntErrorMessages.IsBetweenErrorMessage(key, start.ToString(FluntFormats.DateTimeFormat), end.ToString(FluntFormats.DateTimeFormat)));

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

public int PlaceOrder(double price, double amount, MarketType market)
        {
            string regPrice = "", regAmount = "", method = "", mParams = "";
            switch (market)
            {
                case MarketType.BTCCNY:
					regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F4", CultureInfo.InvariantCulture);
                    break;
                case MarketType.LTCCNY:
					regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
                    break;
                case MarketType.LTCBTC:
					regPrice = price.ToString("F4", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
                    break;
                default://"ALL" is not supported
                    throw new BTCChinaException("PlaceOrder", "N/A", "Market not supported.");
            }
            if (regPrice.StartsWith("-", StringComparison.Ordinal))
                regPrice = "null";
			if (regAmount.StartsWith("-", StringComparison.Ordinal))
            {
                regAmount = regAmount.TrimStart('-');
                method = "sellOrder2";
            }
            else
            {
                method = "buyOrder2";
            }

//          mParams = regPrice + "," + regAmount;
            mParams = "\"" + regPrice + "\",\"" + regAmount + "\"";
            //not default market
            if (market != MarketType.BTCCNY)
                mParams += ",\"" + System.Enum.GetName(typeof(MarketType), market) + "\"";

            var response = DoMethod(BuildParams(method, mParams));
	        var jsonObject = JObject.Parse(response);
	        var orderId = jsonObject.Value<int>("result");

	        return orderId;
        }

19 View Source File : TimeInterval.cs
License : MIT License
Project Creator : AndreyAkinshin

[Pure, NotNull]
        public string ToString(
            [CanBeNull] TimeUnit timeUnit,
            [CanBeNull] string format = null,
            [CanBeNull] IFormatProvider formatProvider = null,
            [CanBeNull] UnitPresentation unitPresentation = null)
        {
            timeUnit ??= TimeUnit.GetBestTimeUnit(Nanoseconds);
            format ??= DefaultFormat;
            formatProvider ??= DefaultCultureInfo.Instance;
            unitPresentation ??= UnitPresentation.Default;
            double unitValue = TimeUnit.Convert(Nanoseconds, TimeUnit.Nanosecond, timeUnit);
            if (unitPresentation.IsVisible)
            {
                string unitName = timeUnit.Name.PadLeft(unitPresentation.MinUnitWidth);
                return $"{unitValue.ToString(format, formatProvider)} {unitName}";
            }

            return unitValue.ToString(format, formatProvider);
        }

19 View Source File : DBEntryUnitAircraftData.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal string GetRadioreplacedtring()
        {
            return $"{RadioFrequency.ToString("F1", NumberFormatInfo.InvariantInfo)} {RadioModulation}";
        }

19 View Source File : DoubleExtensions.cs
License : MIT License
Project Creator : AndreyAkinshin

public static string ToStringInvariant(this double value, string format) => value.ToString(format, DefaultCultureInfo.Instance);

19 View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000

public override string? Readreplacedtring(ISqDataRecordReader recordReader)
            => this.Read(recordReader)?.ToString("F", CultureInfo.InvariantCulture);

19 View Source File : ConfidenceInterval.cs
License : MIT License
Project Creator : AndreyAkinshin

public string ToString(string format, IFormatProvider formatProvider = null, bool showLevel = true)
        {
            formatProvider ??= DefaultCultureInfo.Instance;

            var builder = new StringBuilder();
            builder.Append('[');
            builder.Append(Lower.ToString(format, formatProvider));
            builder.Append("; ");
            builder.Append(Upper.ToString(format, formatProvider));
            builder.Append("]");
            if (showLevel)
            {
                builder.Append(" (CI ");
                builder.Append(ConfidenceLevel.ToString());
                builder.Append(")");
            }

            return builder.ToString();
        }

19 View Source File : GeneratorTools.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal static object FormatRadioFrequency(double radioFrequency)
        {
            return radioFrequency.ToString("F1", NumberFormatInfo.InvariantInfo);
        }

19 View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin

private static void RegisterDefaultConverters()
		{
			//TODO: there is too much generic type combinations! need to refactor this ...

			RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
			RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
			RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
			RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
			RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
			RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
			RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
			RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
			RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
			RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
			RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
			RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
			RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);

			RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<int, bool>((value) => value != 0);
			RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<int, byte>((value) => checked((byte)value));
			RegisterUnsafe<int, short>((value) => checked((short)value));
			RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<int, uint>((value) => (uint)value);
			RegisterUnsafe<int, long>((value) => value);
			RegisterUnsafe<int, ulong>((value) => (ulong)value);
			RegisterUnsafe<int, double>((value) => value);
			RegisterUnsafe<int, float>((value) => checked((float)value));
			RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<uint, bool>((value) => value != 0);
			RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<uint, byte>((value) => checked((byte)value));
			RegisterUnsafe<uint, short>((value) => checked((short)value));
			RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<uint, int>((value) => (int)value);
			RegisterUnsafe<uint, long>((value) => value);
			RegisterUnsafe<uint, ulong>((value) => value);
			RegisterUnsafe<uint, double>((value) => value);
			RegisterUnsafe<uint, float>((value) => checked((float)value));

			RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<long, bool>((value) => value != 0);
			RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<long, byte>((value) => checked((byte)value));
			RegisterUnsafe<long, short>((value) => checked((short)value));
			RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<long, int>((value) => checked((int)value));
			RegisterUnsafe<long, uint>((value) => (uint)value);
			RegisterUnsafe<long, ulong>((value) => (ulong)value);
			RegisterUnsafe<long, double>((value) => checked((double)value));
			RegisterUnsafe<long, float>((value) => checked((float)value));
			RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
			RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));

			RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ulong, bool>((value) => value != 0);
			RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
			RegisterUnsafe<ulong, short>((value) => checked((short)value));
			RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<ulong, int>((value) => checked((int)value));
			RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
			RegisterUnsafe<ulong, long>((value) => checked((long)value));
			RegisterUnsafe<ulong, double>((value) => checked((double)value));
			RegisterUnsafe<ulong, float>((value) => checked((float)value));
			RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));

			RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<short, bool>((value) => value != 0);
			RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<short, byte>((value) => checked((byte)value));
			RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<short, int>((value) => value);
			RegisterUnsafe<short, uint>((value) => checked((uint)value));
			RegisterUnsafe<short, long>((value) => value);
			RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<short, double>((value) => value);
			RegisterUnsafe<short, float>((value) => value);
			RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ushort, bool>((value) => value != 0);
			RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
			RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ushort, short>((value) => checked((short)value));
			RegisterUnsafe<ushort, int>((value) => value);
			RegisterUnsafe<ushort, uint>((value) => value);
			RegisterUnsafe<ushort, long>((value) => value);
			RegisterUnsafe<ushort, ulong>((value) => value);
			RegisterUnsafe<ushort, double>((value) => value);
			RegisterUnsafe<ushort, float>((value) => value);

			RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<byte, bool>((value) => value != 0);
			RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<byte, short>((value) => value);
			RegisterUnsafe<byte, ushort>((value) => value);
			RegisterUnsafe<byte, int>((value) => value);
			RegisterUnsafe<byte, uint>((value) => value);
			RegisterUnsafe<byte, long>((value) => value);
			RegisterUnsafe<byte, ulong>((value) => value);
			RegisterUnsafe<byte, double>((value) => value);
			RegisterUnsafe<byte, float>((value) => value);
			RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<sbyte, bool>((value) => value != 0);
			RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
			RegisterUnsafe<sbyte, short>((value) => value);
			RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<sbyte, int>((value) => value);
			RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
			RegisterUnsafe<sbyte, long>((value) => value);
			RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<sbyte, double>((value) => value);
			RegisterUnsafe<sbyte, float>((value) => value);

			RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
			RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
			RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
			RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<float, byte>((value) => checked((byte)value));
			RegisterUnsafe<float, short>((value) => checked((short)value));
			RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<float, int>((value) => checked((int)value));
			RegisterUnsafe<float, uint>((value) => (uint)value);
			RegisterUnsafe<float, long>((value) => checked((long)value));
			RegisterUnsafe<float, ulong>((value) => (ulong)value);
			RegisterUnsafe<float, double>((value) => value);

			RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
			RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
			RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
			RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<double, byte>((value) => checked((byte)value));
			RegisterUnsafe<double, short>((value) => checked((short)value));
			RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<double, int>((value) => checked((int)value));
			RegisterUnsafe<double, uint>((value) => (uint)value);
			RegisterUnsafe<double, long>((value) => checked((long)value));
			RegisterUnsafe<double, ulong>((value) => (ulong)value);
			RegisterUnsafe<double, float>((value) => checked((float)value));

			RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
			RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
			RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
			RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
			RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
			RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
			RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));

			RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
			RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
			RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
			RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
			RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
			RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
			RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
			RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
			RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
			RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
			RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
			RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
			RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
			RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
			RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
			RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));

			RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
			RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
			RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
			RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));

			RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));

			RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
			RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);

			RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
			RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
			RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
			RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
			RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
			RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);

			RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
			RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
			RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);

			RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
			RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
			RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));

			//REVIEW: this should go in the Tuples layer !
			RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
			RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
			RegisterUnsafe<Slice, bool>((value) => value.ToBool());
			RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
			RegisterUnsafe<Slice, byte>((value) => value.ToByte());
			RegisterUnsafe<Slice, short>((value) => value.ToInt16());
			RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
			RegisterUnsafe<Slice, int>((value) => value.ToInt32());
			RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
			RegisterUnsafe<Slice, long>((value) => value.ToInt64());
			RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
			RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
			RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
			RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
			RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
		}

19 View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000

public override string Readreplacedtring(ISqDataRecordReader recordReader)
            => this.ReadNullable(recordReader)?.ToString("F", CultureInfo.InvariantCulture)
               ?? throw new SqExpressException($"Null value is not expected in non nullable column '{this.ColumnName.Name}'");

19 View Source File : TableColumnsTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public void TestDouble()
        {
            replacedert.AreEqual(SqQueryBuilder.SqlType.Double, this.Table.ColDouble.SqlType);
            replacedert.AreEqual("[AT].[ColDouble]", this.Table.ColDouble.ToSql());
            replacedert.IsFalse(this.Table.ColDouble.IsNullable);

            DerivedTable dt = new DerivedTable();
            var customColumn = this.Table.ColDouble.AddToDerivedTable(dt);
            replacedert.AreEqual(this.Table.ColDouble.ColumnName, customColumn.ColumnName);
            replacedert.IsTrue(dt.Columns.Contains(customColumn));

            var customColumn2 = this.Table.ColDouble.ToCustomColumn(this.NewSource);
            replacedert.AreEqual(this.Table.ColDouble.ColumnName, customColumn2.ColumnName);

            var reader = new Mock<ISqDataRecordReader>();

            this.Table.ColDouble.Read(reader.Object);
            customColumn.Read(reader.Object);

            reader.Verify(r => r.GetDouble(It.Is<string>(name => name == customColumn.ColumnName.Name)), Times.Exactly(2));

            replacedert.Throws<SqExpressException>(() => this.Table.ColDouble.Readreplacedtring(reader.Object));
            reader.Setup(r => r.GetNullableDouble(It.Is<string>(name => name == customColumn.ColumnName.Name))).Returns(-12.34567);
            replacedert.AreEqual((-12.34567).ToString("F", CultureInfo.InvariantCulture), this.Table.ColDouble.Readreplacedtring(reader.Object));

            replacedert.AreEqual(12.34567.ToString("F", CultureInfo.InvariantCulture), this.Table.ColDouble.FromString(12.34567.ToString("F", CultureInfo.InvariantCulture)).ToSql());
            replacedert.Throws<SqExpressException>(() => this.Table.ColDouble.FromString(null));
        }

19 View Source File : GrblSettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension

private async void ButtonApply_Click(object sender, RoutedEventArgs e)
        {
            List<Tuple<int, double>> ToSend = new List<Tuple<int, double>>();

            foreach (KeyValuePair<int, double> kvp in CurrentSettings)
            {
                double newval;

                if (!double.TryParse(SettingsBoxes[kvp.Key].Text, System.Globalization.NumberStyles.Float, Util.Constants.DecimalParseFormat, out newval))
                {
                    MessageBox.Show($"Value \"{SettingsBoxes[kvp.Key].Text}\" is invalid for Setting \"{Util.GrblCodeTranslator.Settings[kvp.Key].Item1}\"");
                    return;
                }

                if (newval == kvp.Value)
                    continue;

                ToSend.Add(new Tuple<int, double>(kvp.Key, newval));
            }

            if (SendLine == null)
                return;

            foreach (Tuple<int, double> setting in ToSend)
            {
                SendLine.Invoke($"${setting.Item1}={setting.Item2.ToString(Util.Constants.DecimalOutputFormat)}");
                CurrentSettings[setting.Item1] = setting.Item2;
                await Task.Delay(Properties.Settings.Default.SettingsSendDelay);
            }
        }

19 View Source File : ExpressionUtility.cs
License : MIT License
Project Creator : actions

internal static String FormatValue(
            ISecretMasker secretMasker,
            Object value,
            ValueKind kind)
        {
            switch (kind)
            {
                case ValueKind.Null:
                    return ExpressionConstants.Null;

                case ValueKind.Boolean:
                    return ((Boolean)value) ? ExpressionConstants.True : ExpressionConstants.False;

                case ValueKind.Number:
                    var strNumber = ((Double)value).ToString(ExpressionConstants.NumberFormat, CultureInfo.InvariantCulture);
                    return secretMasker != null ? secretMasker.MaskSecrets(strNumber) : strNumber;

                case ValueKind.String:
                    // Mask secrets before string-escaping.
                    var strValue = secretMasker != null ? secretMasker.MaskSecrets(value as String) : value as String;
                    return $"'{StringEscape(strValue)}'";

                case ValueKind.Array:
                case ValueKind.Object:
                    return kind.ToString();

                default: // Should never reach here.
                    throw new NotSupportedException($"Unable to convert to realized expression. Unexpected value kind: {kind}");
            }
        }

19 View Source File : JsonSchemaToXsd.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private static string FormatDouble(double value)
        {
            return value.ToString("G", CultureInfo.InvariantCulture);
        }

See More Examples