private static double SetUpToDouble(string sValue) { System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CurrentCulture; System.Globalization.NumberFormatInfo nf = ci.NumberFormat; return(Convert.ToDouble(sValue.Replace(",", nf.NumberDecimalSeparator).Replace(".", nf.NumberDecimalSeparator))); }
static Lexer() { var culture = new System.Globalization.CultureInfo("ja-JP"); NFI = culture.NumberFormat; ope1.Add('(', TokenKind.Lparen); ope1.Add(')', TokenKind.Rparen); ope1.Add('{', TokenKind.LCurly); ope1.Add('}', TokenKind.RCurly); ope1.Add('+', TokenKind.Plus); ope1.Add('-', TokenKind.Minus); ope1.Add('*', TokenKind.Multi); ope1.Add('/', TokenKind.Divi); ope1.Add('<', TokenKind.Less); ope1.Add('>', TokenKind.Great); ope1.Add('=', TokenKind.Assign); ope1.Add('.', TokenKind.Dot); ope1.Add(',', TokenKind.Comma); ope1.Add(':', TokenKind.Colon); ope1.Add(';', TokenKind.Semicolon); ope2.Add("==", TokenKind.Equal); ope2.Add("!=", TokenKind.NotEq); ope2.Add("<=", TokenKind.LessEq); ope2.Add(">=", TokenKind.GreatEq); }
/// <summary> /// Gets the number format info. (to avoid problems with the culture) /// </summary> /// <returns></returns> public static System.Globalization.NumberFormatInfo GetNumberFormatInfo() { System.Globalization.NumberFormatInfo info = new System.Globalization.NumberFormatInfo(); info.NumberDecimalSeparator = "."; info.NumberGroupSeparator = ","; return info; }
static EnvironmentFunctions() { System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; _NumberFormatInfo = (System.Globalization.NumberFormatInfo)ci.NumberFormat.Clone(); _Dot = Convert.ToChar("."); _Coma = Convert.ToChar(","); }
/// <summary> /// Constructor /// </summary> /// <param name="format"></param> public NumericViewer(string format) { if (!string.IsNullOrEmpty(format)) { if (format.Length != 2) { throw new ArgumentException("format's length shoud be 2!", "format"); } if (!formatNumbers.ContainsKey(format)) { System.Globalization.NumberFormatInfo formatNumber2 = (System.Globalization.CultureInfo.CurrentCulture.NumberFormat).Clone() as System.Globalization.NumberFormatInfo; formatNumber2.CurrencySymbol = " "; //format[0].ToString(); formatNumber2.CurrencyDecimalDigits = Convert.ToInt32(format[1].ToString()); formatNumber2.CurrencyNegativePattern = 2; // $-n formatNumber2.NumberDecimalDigits = formatNumber2.CurrencyDecimalDigits; formatNumber2.NumberNegativePattern = 2; formatNumbers.Add(format, formatNumber2); } m_format = formatNumbers[format]; } else { if (!formatNumbers.ContainsKey(s_defaultFormatName)) { System.Globalization.NumberFormatInfo formatNumber2 = (System.Globalization.CultureInfo.CurrentCulture.NumberFormat).Clone() as System.Globalization.NumberFormatInfo; formatNumber2.CurrencySymbol = " "; formatNumbers.Add(s_defaultFormatName, formatNumber2); } m_format = formatNumbers[s_defaultFormatName]; } }
static WorkData() { colonNumberFormat = new System.Globalization.NumberFormatInfo(); colonNumberFormat.NumberDecimalSeparator = ","; pointNumberFormat = new System.Globalization.NumberFormatInfo(); pointNumberFormat.NumberDecimalSeparator = "."; }
public Engine(string connectionstring) { tofile = false; sifre = ""; STR_HataMesaji = ""; sql = ""; FiyatGrupKodu = ""; try { CihazID = new TWinApi().GetIdValid(); } catch { } try { dat = new Database(connectionstring); } catch (Exception ex) { throw new Exception(ex.Message); } int[] numberformatseperator = { 3, 3, 3, 3, 3, 3, 3, 3, 3 }; cfi = new System.Globalization.CultureInfo("en-US", true).NumberFormat; cfi.CurrencyDecimalDigits = 2; cfi.CurrencyDecimalSeparator = "."; cfi.CurrencyGroupSeparator = ","; cfi.CurrencyGroupSizes = numberformatseperator; cfi.CurrencySymbol = ""; cfi.CurrencySymbol = "TL"; cfi.NumberDecimalDigits = 2; cfi.NumberDecimalSeparator = "."; cfi.NumberGroupSeparator = ","; cfi.NumberGroupSizes = numberformatseperator; nfi = new System.Globalization.CultureInfo("en-US", true).NumberFormat; nfi.CurrencyDecimalDigits = 3; nfi.CurrencyDecimalSeparator = "."; nfi.CurrencyGroupSeparator = ","; nfi.CurrencyGroupSizes = numberformatseperator; nfi.CurrencySymbol = ""; nfi.CurrencySymbol = ""; nfi.NumberDecimalDigits = 3; nfi.NumberDecimalSeparator = "."; nfi.NumberGroupSeparator = ","; nfi.NumberGroupSizes = numberformatseperator; if (!Connect) { return; } }
public UIDTO(DataInfo info) { System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; ni = (System.Globalization.NumberFormatInfo)ci.NumberFormat.Clone(); //ni.NumberDecimalSeparator = "."; this.info = info; }
private static void Save2KML(Hashtable styles, YMapsPlacemark[] pms, string filename, string name) { System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; System.Globalization.NumberFormatInfo ni = (System.Globalization.NumberFormatInfo)ci.NumberFormat.Clone(); ni.NumberDecimalSeparator = "."; FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sw.WriteLine("<kml>"); sw.WriteLine("\t<Document>"); sw.WriteLine("\t\t<Folder>"); sw.WriteLine("\t\t<name>" + name + "</name>"); foreach (YMapsPlacemark pm in pms) { sw.WriteLine("\t\t\t<Placemark>"); sw.WriteLine("\t\t\t\t<name>" + System.Security.SecurityElement.Escape(pm.description) + "</name>"); sw.WriteLine("\t\t\t\t<description><![CDATA[" + pm.description + "]]></description>"); sw.WriteLine("\t\t\t\t<styleUrl>" + (pm.style == "" ? "#nocion" : "#" + pm.style) + "</styleUrl>"); sw.WriteLine("\t\t\t\t<Point><coordinates>" + String.Format(ni, "{0},{1},0", pm.x, pm.y) + "</coordinates></Point>"); sw.WriteLine("\t\t\t</Placemark>"); } ; sw.WriteLine("\t\t</Folder>"); sw.WriteLine("\t<Style id=\"noicon\"><IconStyle><Icon><href>images/noicon.png</href></Icon></IconStyle></Style>"); foreach (string key in styles.Keys) { sw.WriteLine("\t<Style id=\"" + key + "\"><IconStyle><Icon><href>" + styles[key].ToString() + "</href></Icon></IconStyle></Style>"); } sw.WriteLine("\t</Document>"); sw.WriteLine("</kml>"); sw.Close(); fs.Close(); }
/* * Формирование полного файла данных для решения. * Входные параметры: * 1) строка с именем файла, куда следует производить запись; * 2) массив чисел с плавающей точкой содержащих численные данные; * 3) массив строк содержащих параметры решения. */ public static void fillDataFile(string filePath, double[] data, string[] parameters) { try { System.IO.File.WriteAllText(filePath, "var data = [];\nvar params = {};\n"); for (int i = 0; i < data.Length; ++i) { System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo(); provider.NumberDecimalSeparator = "."; provider.NumberGroupSeparator = ","; provider.NumberGroupSizes = new int[] { 3 }; System.IO.File.AppendAllText(filePath, "data[" + i.ToString() + "] = " + data[i].ToString(provider) + ";\n"); } for (int i = 0; i < parameters.Length; ++i) { string[] pp = parameters[i].Split(' '); System.IO.File.AppendAllText(filePath, "params." + pp[0] + " = " + pp[1] + ";\n"); } } catch (Exception e) { throw e; } }
// Base 64 : =========================================================================================================================================================================================================== // http://msdn.microsoft.com/en-us/library/System.Convert_methods(v=vs.110).aspx // http://msdn.microsoft.com/en-us/library/8s62fh68(v=vs.110).aspx // http://msdn.microsoft.com/en-us/library/system.convert.frombase64chararray(v=vs.110).aspx public void ConvertFromBaseToBaseInDotNet() { int[] supportedBases = { 2, 8, 10, 16 }; byte[] byteArrayNumbers = { 10, 65, Byte.MinValue, Byte.MaxValue }; short[] shortArrayNumbers = { Int16.MinValue, -13621, -18, 12, 19142, Int16.MaxValue }; int[] intArrayNumbers = { Int32.MinValue, -19327543, -13621, -18, 12, 19142, Int32.MaxValue }; long[] longArrayNumbers = { Int64.MinValue, -193275430, -13621, -18, 12, 1914206117, Int64.MaxValue }; foreach (int baseValue in supportedBases) { Debug.WriteLine("Base {0} conversion: For Byte ", baseValue); foreach (byte number in byteArrayNumbers) { Debug.WriteLine(" {0, -5} --> {1}", number, Convert.ToString(number, baseValue)); } Debug.WriteLine("Base {0} conversion: For Short ", baseValue); foreach (short number in shortArrayNumbers) { Debug.WriteLine(" {0, -5} --> {1}", number, Convert.ToString(number, baseValue)); } } System.Globalization.NumberFormatInfo numberFormatInfo = new System.Globalization.NumberFormatInfo(); numberFormatInfo.NegativeSign = "~"; numberFormatInfo.PositiveSign = "!"; foreach (int number in byteArrayNumbers) { Debug.WriteLine("{0,-12} --> {1,12}", Convert.ToString(number, System.Globalization.CultureInfo.InvariantCulture), Convert.ToString(number, numberFormatInfo)); } }
/// <summary> /// The real operation to be executed by the functoid /// You need change this code and add your logic here /// </summary> public string ParseToNumber(string value, string decimalSeparator, string groupSeparator) { if (string.IsNullOrEmpty(value)) { return("0"); } System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo(); if (string.IsNullOrEmpty(decimalSeparator)) { provider.NumberDecimalSeparator = "."; } else { provider.NumberDecimalSeparator = decimalSeparator; provider.NumberGroupSeparator = groupSeparator; } string number = string.Empty; number = Convert.ToInt64(Convert.ToDecimal(value, provider)).ToString(); return(number); }
static Parser() { // Set US/UK decimal point, regardless of culture System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; numberFormat = (System.Globalization.NumberFormatInfo)ci.NumberFormat.Clone(); numberFormat.NumberDecimalSeparator = "."; }
protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); System.Globalization.NumberFormatInfo fi = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; string c = e.KeyChar.ToString(); if (char.IsDigit(c, 0)) { return; } if ((SelectionStart == 0) && (c.Equals(fi.NegativeSign) && _enableNegative)) { return; } // copy/paste if ((((int)e.KeyChar == 22) || ((int)e.KeyChar == 3)) && ((ModifierKeys & Keys.Control) == Keys.Control)) { return; } if (e.KeyChar == '\b') { return; } e.Handled = true; }
/// <summary> /// 将数字添加千分符 /// </summary> /// <param name="i"></param> /// <returns></returns> public static string tPoints(int i) { System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); nfi.NumberDecimalDigits = 0; string ii = i.ToString("N", nfi); return ii; }
public void insertResult() { try { System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo(); provider.NumberDecimalSeparator = ","; provider.NumberGroupSeparator = "."; decimal carb = Convert.ToDecimal(txtpuis.Text, provider); decimal ht0 = Convert.ToDecimal(haute.Text, provider); decimal ll0 = Convert.ToDecimal(test.Text, provider); string _strConn = ConfigurationManager.ConnectionStrings["LocalMySqlServer"].ConnectionString; using (MySqlConnection cn = new MySqlConnection(_strConn)) { decimal sulta = (ht0 * ll0); string resulta = sulta.ToString(); //puissance decimal reltp = sulta * carb; string resultpw = reltp.ToString(); string lt = TxtLed.Text; cn.Open(); // Requête SQL string query = "INSERT INTO resultat (type_Led, Puissance_Total,Nombre_Led,Alimantation) VALUES ('" + lt + "','" + resultpw + "','" + resulta + "','" + nbV.Text + "')"; MySqlCommand cmd = new MySqlCommand(query, cn); cmd.ExecuteNonQuery(); } } catch { } }
/// <summary> /// Laskenappia klikatessa syötetään syötteeet paceLabelille. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { if (ValidateChildren()) { double matka; System.Globalization.NumberFormatInfo format = new System.Globalization.NumberFormatInfo(); format.NumberDecimalSeparator = ","; try { TimeSpan aika = TimeSpan.Parse(timeTextBox.Text); try { matka = double.Parse(matkaNumberTextbox.Text, format); } catch (Exception exc) { format.NumberDecimalSeparator = "."; matka = double.Parse(matkaNumberTextbox.Text, format); } double pace = aika.TotalMinutes / matka; paceLabel.Time = aika; paceLabel.Distance = matka; } catch (Exception ex) { } } }
static List <StockItem> ParseNasdaq(string txtstream) { // Date, Close/Last, Volume, Open, High, Low\n01/25/2021, $5.84, 44045480, $6.11, $7.3, $5.16\n... List <StockItem> data = new List <StockItem>(); int start = 0; int last = 0; bool has_line = true; System.Globalization.NumberFormatInfo format = new System.Globalization.NumberFormatInfo() { NumberDecimalSeparator = "." }; while (true) { string line = GetLine(txtstream, start, out last); if (line.Length == 0) { break; } start = last; StockItem slot = new StockItem(); bool has_value = ParseNasdaqLine(line, ref slot, format); if (has_value == true) { data.Add(slot); } } return(data); }
/// <summary> /// Process a variable set of string data parameters. Used only in wrap mode. /// </summary> /// <param name="errorMessage">Error message</param> /// <param name="data">Variadic string parameters</param> /// <returns>True if data processing was OK</returns> private bool processAsciiNonDomainData(ref string errorMessage, params string[] data) { try { System.Globalization.NumberFormatInfo format = new System.Globalization.NumberFormatInfo(); for (int i = 0; i < data.Length; ++i) { double parsed = double.Parse(data[i], format); _asciiValues.Add(parsed); } return(true); } catch (ArgumentNullException exception) { errorMessage = exception.Message; } catch (FormatException exception) { errorMessage = exception.Message; } catch (OverflowException exception) { errorMessage = exception.Message; } return(false); }
static void SaveStockDataCSV(List <StockItem> data, string filename) { using (System.IO.StreamWriter file = new System.IO.StreamWriter(filename)) { string header = string.Concat ("Fecha, ", "Ultimo, ", "Volumen, ", "Apertura, ", "Maximo, ", "Minimo"); file.WriteLine(header); System.Globalization.NumberFormatInfo format = new System.Globalization.NumberFormatInfo() { NumberDecimalSeparator = "." }; for (int i = data.Count - 1; i >= 0; i--) { StockItem item = data[i]; DateTime date = new DateTime(item.year, item.month, item.day); string datetxt = date.ToString("yyyy-MM-dd"); string last = Convert.ToString(item.last, format); string volumen = Convert.ToString(item.volumen, format); string open = Convert.ToString(item.open, format); string high = Convert.ToString(item.high, format); string low = Convert.ToString(item.low, format); string line = string.Concat (datetxt, ", ", last, ", ", volumen, ", ", open, ", ", high, ", ", low); file.WriteLine(line); } } }
public ViewOrderDetailEdit() : base() { rex = new Regex(@"(?<int>\d*)?(?<sep>.)?(?<dec>\d*)?"); ni = (System.Globalization.NumberFormatInfo)System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.Clone(); ni.NumberDecimalSeparator = "."; this.Resize(this.NRows, this.NColumns+1 ); spinprice.FocusGrabbed += this.OnActive; spinprice.IsEditable = false; spinquant.FocusGrabbed += this.OnActive; spinquant.IsEditable = false; Button butclearprice; butclearprice = new Button(); butclearprice.Add( new Image(Stock.Clear, IconSize.Button) ); butclearprice.Clicked += OnClearPrice; butclearprice.CanFocus = false; Button butclearquant; butclearquant = new Button(); butclearquant.Add( new Image(Stock.Clear, IconSize.Button) ); butclearquant.Clicked += OnClearQuant; butclearquant.CanFocus = false; this.Attach(butclearprice,2,3,1,2,AttachOptions.Expand,AttachOptions.Fill,0,0); this.Attach(butclearquant,2,3,2,3,AttachOptions.Expand,AttachOptions.Fill,0,0); this.ShowAll(); }
private void buttonAddToReferences_Click(object sender, EventArgs e) { System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; nfi.NumberGroupSeparator = ","; // find designator colum int columDesignator = 0; attribCount = 0; // for (int colDes = 0; colDes < myDataGridView.Rows[0].Cells.Count; colDes++) // { // if (myDataGridView.Columns[colDes].HeaderText.ToLower().Trim() == "designator") // { // columDesignator = colDes; // break; // } // } columDesignator = comboBoxREfColum.SelectedIndex; for (int rows = 0; rows < myDataGridView.Rows.Count - 1; rows++) { myDataGridView.Rows[rows].Cells[columDesignator].Style.BackColor = Color.Red; string Designators = myDataGridView.Rows[rows].Cells[columDesignator].Value.ToString(); Designators = CreateNewRefList(Designators); string[] desList = Designators.Split(','); foreach (string CompDesignator in desList) { ICMPObject cmp = GetComponent(CompDesignator.Trim()); if (cmp == null) { continue; } for (int col = 0; col < myDataGridView.Rows[rows].Cells.Count; col++) { if (col == columDesignator) { continue; } if (myDataGridView.Columns[col].HeaderText.ToLower() == "height") { IComponentSpecifics cs = (IComponentSpecifics)cmp.GetSpecifics(); cs.Height = float.Parse(myDataGridView.Rows[rows].Cells[col].Value.ToString().Replace(",", "."), nfi); cmp.SetSpecifics(cs); } else { cmp.AddComponentAttribute(myDataGridView.Columns[col].HeaderText, myDataGridView.Rows[rows].Cells[col].Value.ToString(), false); // HeaderText.toLower() ?? myDataGridView.Rows[rows].Cells[columDesignator].Style.BackColor = Color.GreenYellow; } } } } if (attribCount > 0) { MessageBox.Show(attribCount.ToString() + " : Components changed, " + PCBI_Parent.GetCurrentStep().GetAllCMPObjects().Count.ToString() + " Components in design", "Finished"); } else { MessageBox.Show("No attributes added", "Finished without success"); } }
static FileSizeConverter() { /* * * // base2/binary "computer" units * * knownUnits = new Dictionary<string, long> * { * { "", 1L }, // no unit is same as unit B(yte) * { "B", 1L }, * { "KB", 1024L }, * { "MB", 1024L * 1024L}, * { "GB", 1024L * 1024L * 1024L}, * { "TB", 1024L * 1024L * 1024L * 1024L} * // fill rest as needed * }; * */ // decimal "contraction" units knownUnits = new Dictionary <string, long> { { "", 1L }, { "M", 1000L * 1000L }, // million { "B", 1000L * 1000L * 1000L } // billion (usa) // fill rest as needed }; numberFormat = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; }
public bool CheckForValidReturnQty(string xmlDoc, ref string errorMessage) { bool isValid = true; System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); nfi.PercentDecimalDigits = Common.DisplayAmountRounding; string strRoundingZeroesFormat = Common.GetRoundingZeroes(Common.DisplayQtyRounding); //"0.00"; DataTaskManager dtDataMgr = new DataTaskManager(); using (DataTaskManager dtManager = new DataTaskManager()) { DBParameterList dbParam = new DBParameterList(); dbParam.Add(new DBParameter(Common.PARAM_DATA, xmlDoc, DbType.String)); dbParam.Add(new DBParameter(Common.PARAM_OUTPUT, string.Empty, DbType.String, ParameterDirection.Output, Common.PARAM_OUTPUT_LENGTH)); using (DataSet ds = dtDataMgr.ExecuteDataSet(SP_CHECK_RET_QTY, dbParam)) { string tempErrCode = dbParam[Common.PARAM_OUTPUT].Value.ToString(); if (!string.IsNullOrEmpty(tempErrCode)) { //errorMessage = Common.GetMessage(tempErr); DataTable dtTemp = ds.Tables[0]; decimal totGRNRecQty = Convert.ToDecimal(dtTemp.Rows[0]["TotalRemainingQty"].ToString()); errorMessage = Common.GetMessage(tempErrCode, totGRNRecQty.ToString(strRoundingZeroesFormat, nfi)); isValid = false; } } } return(isValid); }
private static ScanResult SnipeScanForPokemon(Location location) { var formatter = new System.Globalization.NumberFormatInfo(); formatter.NumberDecimalSeparator = "."; var uri = $"https://pokevision.com/map/data/{location.Latitude.ToString(formatter)}/{location.Longitude.ToString(formatter)}"; ScanResult scanResult; try { var request = WebRequest.CreateHttp(uri); request.Accept = "application/json"; request.Method = "GET"; request.Timeout = 1000; var resp = request.GetResponse(); var reader = new StreamReader(resp.GetResponseStream()); scanResult = JsonConvert.DeserializeObject <ScanResult>(reader.ReadToEnd()); } catch (Exception) { scanResult = new ScanResult() { status = "fail", pokemon = new List <PokemonLocation>() }; } return(scanResult); }
// Restricts the entry of characters to digits (including hex), the negative sign, // the decimal point, and editing keystrokes (backspace). protected override void OnKeyPress(KeyPressEventArgs e) { m_vorher = Text; base.OnKeyPress(e); System.Globalization.NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; string decimalSeparator = numberFormatInfo.NumberDecimalSeparator; string groupSeparator = numberFormatInfo.NumberGroupSeparator; string negativeSign = numberFormatInfo.NegativeSign; string keyInput = e.KeyChar.ToString(); if (Char.IsDigit(e.KeyChar)) { // Digits are OK } else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) || keyInput.Equals(negativeSign)) { // Decimal separator is OK } else if (e.KeyChar == '\b') { // Backspace key is OK } // else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0) // { // // Let the edit control handle control and alt key combinations // } else { e.Handled = true; } }
public static int?ToNullableInteger(this object intValue, System.Globalization.NumberFormatInfo nmFrmInfo) { int?theReturn = null; if (intValue != null) { //if (IsNumeric(intValue) | intValue.ToString() == "0") //{ //theReturn = CDbl(doubleValue.ToString) //first see if it is a float if (double.TryParse(intValue.ToString(), System.Globalization.NumberStyles.Any, nmFrmInfo, out double dbl)) { theReturn = Convert.ToInt32(Math.Floor(dbl)); return(theReturn); } if (int.TryParse(intValue.ToString(), System.Globalization.NumberStyles.Any, nmFrmInfo, out int tmp)) { theReturn = tmp; } // } } return(theReturn); }
protected override void OnTextBoxKeyPress(object source, KeyPressEventArgs e) { base.OnTextBoxKeyPress(source, e); System.Globalization.NumberFormatInfo numberFormat = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; string dec = numberFormat.NumberDecimalSeparator; string group = numberFormat.NumberGroupSeparator; string sign = numberFormat.NegativeSign; string key = e.KeyChar.ToString(); if (!char.IsDigit(e.KeyChar) && key != dec && key != group && key != sign && e.KeyChar != '\b') { if (this.hexadecimal) { if (e.KeyChar >= 'a' && e.KeyChar <= 'f') { return; } if (e.KeyChar >= 'A' && e.KeyChar <= 'F') { return; } } e.Handled = true; } }
private void btnDesviacion_Click(object sender, EventArgs e) { System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; ni = (System.Globalization.NumberFormatInfo)ci.NumberFormat.Clone(); ni.NumberDecimalSeparator = "."; n1 = Double.Parse(txt1.Text, ni); n2 = Double.Parse(txt2.Text, ni); n3 = Double.Parse(txt3.Text, ni); n4 = Double.Parse(txt4.Text, ni); n5 = Double.Parse(txt5.Text, ni); n6 = Double.Parse(txt6.Text, ni); numeros = new double[6]; numeros[0] = n1; numeros[1] = n2; numeros[2] = n3; numeros[3] = n4; numeros[4] = n5; numeros[5] = n6; sumatoria = n1 + n2 + n3 + n4 + n5 + n6; double promedio = sumatoria / 6; label12.Visible = true; double sumaAlCuadrado = numeros.Sum(val => (val - promedio) * (val - promedio)); double desviacion = Math.Sqrt(sumaAlCuadrado / (numeros.Length - 1)); label13.Text = "Respuesta: " + desviacion; label13.Visible = true; }
public ActionResult Checkout() { var loaisp = data.LoaiSPs.ToList(); ViewBag.dssp = loaisp; var loaibv = data.LoaiBVs.ToList().Take(3); ViewBag.dsbv = loaibv; var tt_mn = data.BaiViets.OrderByDescending(x => x.NgayDang).ToList().Take(3); ViewBag.tt_mn = tt_mn; List <CartModel> lscart = GioHang(); int total = 0; foreach (var item in lscart) { total += item.THANHTIEN; } ViewBag.TitlePage = "Thanh toán"; ViewBag.ImageTitle = "/"; System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); nfi.CurrencyDecimalDigits = 0; nfi.CurrencySymbol = ""; ViewBag.total = String.Format(nfi, "{0:c}", total); return(View(lscart)); }
/// <summary> /// Gets the number format info. (to avoid problems with the culture) /// </summary> /// <returns></returns> public static System.Globalization.NumberFormatInfo GetNumberFormatInfo() { System.Globalization.NumberFormatInfo info = new System.Globalization.NumberFormatInfo(); info.NumberDecimalSeparator = "."; info.NumberGroupSeparator = ","; return(info); }
public FormMain() { InitializeComponent(); textBoxMessage.Font = new System.Drawing.Font(System.Drawing.SystemFonts.DefaultFont.FontFamily, 15); dataGridViewMessages.AutoGenerateColumns = false; dataGridViewMessages.DataSource = DataSetNbuExplorer.DefaultMessageView; fileSizeFormat = new System.Globalization.NumberFormatInfo(); fileSizeFormat.NumberGroupSeparator = " "; fileSizeFormat.NumberDecimalDigits = 0; appTitle = this.Text; this.Icon = Properties.Resources.icon_phone; this.tsPreview.Image = Properties.Resources.icon_view_bottom.ToBitmap(); this.tsLargeIcons.Image = Properties.Resources.icon_view_multicolumn.ToBitmap(); this.tsDetails.Image = Properties.Resources.icon_view_detailed.ToBitmap(); this.exportSelectedFilesToolStripMenuItem.Image = Properties.Resources.icon_document_save.ToBitmap(); this.exportSelectedFilesToolStripMenuItem1.Image = Properties.Resources.icon_document_save.ToBitmap(); this.exportSelectedFolderToolStripMenuItem.Image = Properties.Resources.icon_save_all.ToBitmap(); this.exportToolStripMenuItem.Image = Properties.Resources.icon_save_all.ToBitmap(); this.exportAllToolStripMenuItem.Image = Properties.Resources.icon_save_all.ToBitmap(); this.tsExportMessages.Image = Properties.Resources.icon_save_all.ToBitmap(); exportSelectedFilesToolStripMenuItem1.Font = new Font(exportSelectedFilesToolStripMenuItem1.Font, FontStyle.Bold); this.textBoxPreview.Dock = DockStyle.Fill; listViewFiles.ListViewItemSorter = fic; listViewFiles_Resize(this, EventArgs.Empty); listViewFiles_SelectedIndexChanged(this, EventArgs.Empty); recountTotal(); }
public AsteroidsCSVReader(string pathCsvFile, int anzKopfzeilen = 1) { // Prüfen, ob die Datei existiert if (System.IO.File.Exists(pathCsvFile)) { // sonst: Datei mit Reader öffnen reader = new System.IO.StreamReader(pathCsvFile); // Kopfzeilen überspringen for (int i = 0; i < anzKopfzeilen; i++) { if (!reader.EndOfStream) { reader.ReadLine(); } else { throw new ArgumentException("Es fehlen Kopfzeilen in der Datei " + pathCsvFile); } } // Information zu Formatierung von Gleitkommawerten in der amerikanischen Kultur bestimmen nif = new System.Globalization.CultureInfo("en-US").NumberFormat; } else { // wenn nicht, Fehler melden throw new ArgumentException("Die csv- Datei " + pathCsvFile + " existiert nicht"); } }
private void tbxCount1_TextChanged(object sender, EventArgs e) { TextBox t = sender as TextBox; int num; double cnt = (count == 0 ? 1 : count); double donasi = Math.Round((Convert.ToSingle(lblPrice.Text) / Math.Round(cnt, 3)), 2); if (tbxCount1.Text != "") { if (count.ToString() != tbxCount1.Text) { System.Globalization.NumberFormatInfo numberformat = new System.Globalization.NumberFormatInfo(); double curCnt = Convert.ToDouble(tbxCount1.Text.Replace(",", numberformat.CurrencyDecimalSeparator).Replace(".", numberformat.CurrencyDecimalSeparator), numberformat); //if (i == 1) lblOnePrice.Text = Math.Round(curCnt * donasi).ToString(); } else { lblOnePrice.Text = lblPrice.Text; } } string d = donasi.ToString(); //if (d.IndexOf(".")!=-1) //lblOne.Text = d.Remove(d.IndexOf(".")); //else //lblOne.Text = d; }
public void testEvaluateTrendsCharacteristics() { double[] data = new double[3793]; int segmentsNumber; SegmentType[] timeSeriesTrends; TimeSeriesTrends instance = new TimeSeriesTrends(); using (System.IO.StreamReader sr = new System.IO.StreamReader("TimeSeriesData.dat")) { System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo(); provider.NumberDecimalSeparator = "."; string dataLine; int i = 0; while ((dataLine = sr.ReadLine()) != null) { data[i++] = Convert.ToDouble(dataLine, provider); } } segmentsNumber = 20; timeSeriesTrends = instance.makeTrendsAlghoritm(data, segmentsNumber); TrendsCharacteristics instanceTrends = new TrendsCharacteristics(); TrendDataType[] result = instanceTrends.evaluateTrendsCharacteristics(timeSeriesTrends, data); }
//大多数需要有给定格式和文化ToString方法的类型都跟数值有关, 用处比如给不同国家的用户显示钱数(钱数的显示方法, 这个国家的货币符号等问题) //1. 使用FCL中的IFormattable static void UseIFormattableFCL() { double price = 2350.58; //Object.Tostring, double重写了这个方法, 现在单纯显示这个数字 string defaultDisplay = price.ToString(); Console.WriteLine(defaultDisplay); System.Globalization.CultureInfo exampleCulture = new System.Globalization.CultureInfo("zh-CN"); //IFormattabl要求的ToString //带来的变化有: //- 数字显示为2,350.58 这是因为指定了"C", 这个数字的含义是一个货币 //- 前面加了RMB符号, 因为知道了是货币的情况下, 还知道是中国文化 string customDisplay = price.ToString("C", exampleCulture); Console.WriteLine(customDisplay); //*理解第二个参数IFormatProvider //要求一个类提供一些内容, 在知道格式的基础上, 用于选择性应用其中某些内容来构建最终的字符串显示 //如知道是货币格式的基础上, 去IFormatProvider实例中找货币符号 System.Globalization.NumberFormatInfo exampleNumRelated = new System.Globalization.NumberFormatInfo(); //NumberFormatInfo一般以CultureInfo成员的方式来用, 由当前Culture来构造完整的信息 //为了理解, 这里手动新建一个对象并手动设置会用到的内容 //虽然不能看到源代码, 但可以确定double的IFormattable.ToString的内部实现, 在"C"的格式下, 只需要NumberFormatInfo.CurrecySign exampleNumRelated.CurrencySymbol = "%"; customDisplay = price.ToString("C", exampleNumRelated); Console.WriteLine(customDisplay); }
public string ToString(string format, IFormatProvider formatProvider) { string raw = "the string description of MyFormattable Class"; System.Globalization.NumberFormatInfo needs = formatProvider.GetFormat(typeof(System.Globalization.NumberFormatInfo)) as System.Globalization.NumberFormatInfo; if (needs == null) { throw new FormatException(); } switch (format) { case "QI": string symbolNeeded = needs.CurrencySymbol; if (symbolNeeded == null) { throw new FormatException(); } raw += System.Environment.NewLine + symbolNeeded + "in QI MODE" + symbolNeeded; break; default: throw new FormatException(); } return(raw); }
public ParserClass() { System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; ni = (System.Globalization.NumberFormatInfo) ci.NumberFormat.Clone(); ni.NumberDecimalSeparator = "."; }
/// <summary> /// Send tracking data /// </summary> /// <param name="coord">Gps point</param> public void CT(Coordinate coord) { if (coord == null) return; var addict = new StringBuilder(); var format = new System.Globalization.NumberFormatInfo() { NumberDecimalDigits = 6, NumberDecimalSeparator = ".", NumberGroupSeparator = string.Empty }; addict.AppendFormat("L{0}:{1}", coord.Lat.ToString("N6", format), coord.Lon.ToString("N6", format)); addict.AppendFormat("S{0}A{1}H{2}C{3}T{4}", coord.Speed.ToString("N2", format), coord.Alt, coord.HDOP, coord.Course, coord.Timestamp); Send(new Message("T", addict.ToString())); }
public AdminWindow(long userId, System.Globalization.NumberFormatInfo format) { InitializeComponent(); sqlite.Connect(); initialize(); this.format = format; this.userId = userId; comboBoxTables.Focus(); }
/// <summary> /// Laskee nopeuden. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void laskeButton_Click(object sender, EventArgs e) { if (ValidateChildren()) { System.Globalization.NumberFormatInfo format = new System.Globalization.NumberFormatInfo(); format.NumberDecimalSeparator = ","; double d_nopeus = Double.Parse(matkaNumberTextBox1.Text) / Double.Parse(aikaNumberTextBox2.Text); nopeus.Text = string.Format(format, "{0:0.00} km/h", d_nopeus); } }
public Form1() { InitializeComponent(); btnParse.Enabled = false; System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; numberFormatInfo = (System.Globalization.NumberFormatInfo)ci.NumberFormat.Clone(); numberFormatInfo.NumberGroupSeparator = ""; numberFormatInfo.NumberDecimalSeparator = "."; ds = new DataSet(); }
public static string GetString(decimal? value, int decimalDigits = 2) { System.Globalization.NumberFormatInfo format = new System.Globalization.NumberFormatInfo() { CurrencyDecimalDigits = decimalDigits, CurrencyDecimalSeparator = ".", CurrencyGroupSeparator = ",", NumberDecimalSeparator = ".", NumberDecimalDigits = decimalDigits }; return (value.HasValue) ? value.Value.ToString("N", format) : string.Empty; }
/// <summary> /// Convert array of integer in a string /// </summary> /// <param name="values">Values</param> /// <returns>String</returns> public static string IntToText(params int[] values) { if (values.Length == 0) return ""; System.Globalization.NumberFormatInfo info = new System.Globalization.NumberFormatInfo(); info.NumberDecimalSeparator = "."; string temp = values.First().ToString(info); for (int i = 1; i < values.Length; i++) { temp += " " + values[i].ToString(info); } return temp; }
public static bool ParseContiniousTFString(string numString, string denString, out double[] num, out double[] denom) { var format = new System.Globalization.NumberFormatInfo { NumberDecimalSeparator = ".", NegativeSign = "-" }; if (string.IsNullOrWhiteSpace(numString) || string.IsNullOrWhiteSpace(denString)) { num = new double[0]; denom = new double[0]; return false; } string numStr = numString.Trim("[]".ToCharArray()); string denomStr = denString.Trim("[]".ToCharArray()); string[] vals = numStr.Split(" \t\n".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries); num = new double[vals.Length]; for (int i = 0; i < vals.Length; i++) { double val; if (!double.TryParse(vals[i], System.Globalization.NumberStyles.Float, format, out val)) { denom = new double[0]; return false; } num[i] = val; } vals = denomStr.Split(" \t\n".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries); denom = new double[vals.Length]; for (int i = 0; i < vals.Length; i++) { double val; if (!double.TryParse(vals[i], System.Globalization.NumberStyles.Float, format, out val)) { return false; } denom[i] = val; } return true; }
private void GetMineralsPricesFromEveCentral() { // Строки: URI и имя локального файла const string webAddress = "http://eve-central.com/api/evemon"; const string localAddress = "EveCentral.xml"; if(LoadXmlData(webAddress, localAddress)) { try { System.Globalization.NumberFormatInfo info = new System.Globalization.NumberFormatInfo { NumberDecimalSeparator = "." }; using(XmlTextReader reader = new XmlTextReader(localAddress)) { Mineral min = null; while(reader.Read()) { switch(reader.NodeType) { case XmlNodeType.Text: { if(min == null) min = MineralList.Get(reader.Value); else { min.Price = Convert.ToDouble(reader.Value, info); min = null; } break; } } } } } catch(XmlException) { } } }
public override void formatear() { Double value; if (Double.TryParse(textBox1.Text, out value)) { System.Globalization.NumberFormatInfo MyNFI = new System.Globalization.NumberFormatInfo(); MyNFI.NegativeSign = "-"; MyNFI.CurrencyDecimalSeparator = ","; MyNFI.CurrencyGroupSeparator = "."; MyNFI.CurrencySymbol = "$"; textBox1.Text = String.Format(MyNFI, "{0:C2}", value); } else if (new Regex("^[$]" + this.validationRegexString()).IsMatch(textBox1.Text)) { textBox1.Text = textBoxSinSignoPeso(); formatear(); } else textBox1.Text = String.Empty; }
/// <summary> /// Validointi tarkastaa että teksti on desimaaliluku väliltä [Min; Max]. /// </summary> /// <param name="e"></param> protected override void OnValidating(CancelEventArgs e) { System.Globalization.NumberFormatInfo format = new System.Globalization.NumberFormatInfo(); format.NumberDecimalSeparator = ","; try { double arvo = Double.Parse(this.Text, format); if (arvo < Min || Max < arvo) { error.SetError(this, "Ei ole oikealla välillä."); e.Cancel = true; return; } } catch (Exception ex) { try { format.NumberDecimalSeparator = "."; double arvo = Double.Parse(this.Text, format); if (arvo < Min || Max < arvo) { error.SetError(this, "Ei ole oikealla välillä."); e.Cancel = true; return; } } catch (Exception exc) { error.SetError(this, "Ei ole oikeaa muotoa."); e.Cancel = true; this.BackColor = Color.Red; } } base.OnValidating(e); }
public static KF BuildKf(double[] num, double[] den, DenseMatrix measCov, DenseMatrix procCov) { var format = new System.Globalization.NumberFormatInfo { NumberDecimalSeparator = ".", NegativeSign = "-" }; var numStr = new StringBuilder(); foreach (var par in num) { numStr.Append(" " + par.ToString(format)); } var denStr = new StringBuilder(); foreach (var par in den) { denStr.Append(" " + par.ToString(format)); } var ssf = GenerateSensorModel(numStr.ToString(), denStr.ToString(), 0.01); var kf = new KF(ssf, measCov, procCov); return kf; }
/// <summary> /// This method gets metadata about the featuretype to query from 'GetCapabilities' and 'DescribeFeatureType'. /// </summary> private void GetFeatureTypeInfo() { try { _FeatureTypeInfo = new WfsFeatureTypeInfo(); WFSClientHTTPConfigurator config = new WFSClientHTTPConfigurator(_TextResources); _FeatureTypeInfo.Prefix = _NsPrefix; _FeatureTypeInfo.Name = _FeatureType; string featureQueryName = string.IsNullOrEmpty(_NsPrefix) ? _FeatureType : _NsPrefix + ":" + _FeatureType; /***************************/ /* GetCapabilities request / /***************************/ if (_FeatureTypeInfoQueryManager == null) { /* Initialize IXPathQueryManager with configured HttpClientUtil */ _FeatureTypeInfoQueryManager = new XPathQueryManager_CompiledExpressionsDecorator(new XPathQueryManager()); _FeatureTypeInfoQueryManager.SetDocumentToParse(config.configureForWfsGetCapabilitiesRequest(_HttpClientUtil, _GetCapabilitiesURI)); /* Namespaces for XPath queries */ _FeatureTypeInfoQueryManager.AddNamespace(_TextResources.NSWFSPREFIX, _TextResources.NSWFS); _FeatureTypeInfoQueryManager.AddNamespace(_TextResources.NSOWSPREFIX, _TextResources.NSOWS); _FeatureTypeInfoQueryManager.AddNamespace(_TextResources.NSXLINKPREFIX, _TextResources.NSXLINK); } /* Service URI (for WFS GetFeature request) */ _FeatureTypeInfo.ServiceURI = _FeatureTypeInfoQueryManager.GetValueFromNode (_FeatureTypeInfoQueryManager.Compile(_TextResources.XPATH_GETFEATURERESOURCE)); /* If no GetFeature URI could be found, try GetCapabilities URI */ if (_FeatureTypeInfo.ServiceURI == null) _FeatureTypeInfo.ServiceURI = _GetCapabilitiesURI; else if (_FeatureTypeInfo.ServiceURI.EndsWith("?", StringComparison.Ordinal)) _FeatureTypeInfo.ServiceURI = _FeatureTypeInfo.ServiceURI.Remove(_FeatureTypeInfo.ServiceURI.Length - 1); /* URI for DescribeFeatureType request */ string describeFeatureTypeUri = _FeatureTypeInfoQueryManager.GetValueFromNode (_FeatureTypeInfoQueryManager.Compile(_TextResources.XPATH_DESCRIBEFEATURETYPERESOURCE)); /* If no DescribeFeatureType URI could be found, try GetCapabilities URI */ if (describeFeatureTypeUri == null) describeFeatureTypeUri = _GetCapabilitiesURI; else if (describeFeatureTypeUri.EndsWith("?", StringComparison.Ordinal)) describeFeatureTypeUri = describeFeatureTypeUri.Remove(describeFeatureTypeUri.Length - 1); /* Spatial reference ID */ _FeatureTypeInfo.SRID = _FeatureTypeInfoQueryManager.GetValueFromNode( _FeatureTypeInfoQueryManager.Compile(_TextResources.XPATH_SRS), new DictionaryEntry[] { new DictionaryEntry("_param1", featureQueryName) }); /* If no SRID could be found, try '4326' by default */ if (_FeatureTypeInfo.SRID == null) _FeatureTypeInfo.SRID = "4326"; else /* Extract number */ _FeatureTypeInfo.SRID = _FeatureTypeInfo.SRID.Substring(_FeatureTypeInfo.SRID.LastIndexOf(":") + 1); /* Bounding Box */ IXPathQueryManager bboxQuery = _FeatureTypeInfoQueryManager.GetXPathQueryManagerInContext( _FeatureTypeInfoQueryManager.Compile(_TextResources.XPATH_BBOX), new DictionaryEntry[] { new DictionaryEntry("_param1", featureQueryName) }); if (bboxQuery != null) { WfsFeatureTypeInfo.BoundingBox bbox = new WfsFeatureTypeInfo.BoundingBox(); System.Globalization.NumberFormatInfo formatInfo = new System.Globalization.NumberFormatInfo(); formatInfo.NumberDecimalSeparator = "."; string bboxVal = null; if (_WfsVersion == WFSVersionEnum.WFS1_0_0) bbox._MinLat = Convert.ToDouble((bboxVal = bboxQuery.GetValueFromNode(bboxQuery.Compile(_TextResources.XPATH_BOUNDINGBOXMINY))) != null ? bboxVal : "0.0", formatInfo); else if (_WfsVersion == WFSVersionEnum.WFS1_1_0) bbox._MinLat = Convert.ToDouble((bboxVal = bboxQuery.GetValueFromNode(bboxQuery.Compile(_TextResources.XPATH_BOUNDINGBOXMINY))) != null ? bboxVal.Substring(bboxVal.IndexOf(' ') + 1) : "0.0", formatInfo); if (_WfsVersion == WFSVersionEnum.WFS1_0_0) bbox._MaxLat = Convert.ToDouble((bboxVal = bboxQuery.GetValueFromNode(bboxQuery.Compile(_TextResources.XPATH_BOUNDINGBOXMAXY))) != null ? bboxVal : "0.0", formatInfo); else if (_WfsVersion == WFSVersionEnum.WFS1_1_0) bbox._MaxLat = Convert.ToDouble((bboxVal = bboxQuery.GetValueFromNode(bboxQuery.Compile(_TextResources.XPATH_BOUNDINGBOXMAXY))) != null ? bboxVal.Substring(bboxVal.IndexOf(' ') + 1) : "0.0", formatInfo); if (_WfsVersion == WFSVersionEnum.WFS1_0_0) bbox._MinLong = Convert.ToDouble((bboxVal = bboxQuery.GetValueFromNode(bboxQuery.Compile(_TextResources.XPATH_BOUNDINGBOXMINX))) != null ? bboxVal : "0.0", formatInfo); else if (_WfsVersion == WFSVersionEnum.WFS1_1_0) bbox._MinLong = Convert.ToDouble((bboxVal = bboxQuery.GetValueFromNode(bboxQuery.Compile(_TextResources.XPATH_BOUNDINGBOXMINX))) != null ? bboxVal.Substring(0, bboxVal.IndexOf(' ') + 1) : "0.0", formatInfo); if (_WfsVersion == WFSVersionEnum.WFS1_0_0) bbox._MaxLong = Convert.ToDouble((bboxVal = bboxQuery.GetValueFromNode(bboxQuery.Compile(_TextResources.XPATH_BOUNDINGBOXMAXX))) != null ? bboxVal : "0.0", formatInfo); else if (_WfsVersion == WFSVersionEnum.WFS1_1_0) bbox._MaxLong = Convert.ToDouble((bboxVal = bboxQuery.GetValueFromNode(bboxQuery.Compile(_TextResources.XPATH_BOUNDINGBOXMAXX))) != null ? bboxVal.Substring(0, bboxVal.IndexOf(' ') + 1) : "0.0", formatInfo); _FeatureTypeInfo.BBox = bbox; } //Continue with a clone in order to preserve the 'GetCapabilities' response IXPathQueryManager describeFeatureTypeQueryManager = _FeatureTypeInfoQueryManager.Clone(); /******************************/ /* DescribeFeatureType request / /******************************/ /* Initialize IXPathQueryManager with configured HttpClientUtil */ describeFeatureTypeQueryManager.ResetNamespaces(); describeFeatureTypeQueryManager.SetDocumentToParse(config.configureForWfsDescribeFeatureTypeRequest (_HttpClientUtil, describeFeatureTypeUri, featureQueryName)); /* Namespaces for XPath queries */ describeFeatureTypeQueryManager.AddNamespace(_TextResources.NSSCHEMAPREFIX, _TextResources.NSSCHEMA); describeFeatureTypeQueryManager.AddNamespace(_TextResources.NSGMLPREFIX, _TextResources.NSGML); /* Get target namespace */ string targetNs = describeFeatureTypeQueryManager.GetValueFromNode( describeFeatureTypeQueryManager.Compile(_TextResources.XPATH_TARGETNS)); if (targetNs != null) _FeatureTypeInfo.FeatureTypeNamespace = targetNs; /* Get geometry */ string geomType = _GeometryType == GeometryTypeEnum.Unknown ? null : _GeometryType.ToString(); string geomName = null; string geomComplexTypeName = null; /* The easiest way to get geometry info, just ask for the 'gml'-prefixed type-attribute... Simple, but effective in 90% of all cases...this is the standard GeoServer creates.*/ /* example: <xs:element nillable = "false" name = "the_geom" maxOccurs = "1" type = "gml:MultiPolygonPropertyType" minOccurs = "0" /> */ /* Try to get context of the geometry element by asking for a 'gml:*' type-attribute */ IXPathQueryManager geomQuery = describeFeatureTypeQueryManager.GetXPathQueryManagerInContext( describeFeatureTypeQueryManager.Compile(_TextResources.XPATH_GEOMETRYELEMENT_BYTYPEATTRIBUTEQUERY)); if (geomQuery != null) { geomName = geomQuery.GetValueFromNode(geomQuery.Compile(_TextResources.XPATH_NAMEATTRIBUTEQUERY)); /* Just, if not set manually... */ if (geomType == null) geomType = geomQuery.GetValueFromNode(geomQuery.Compile(_TextResources.XPATH_TYPEATTRIBUTEQUERY)); } else { /* Try to get context of a complexType with element ref ='gml:*' - use the global context */ /* example: <xs:complexType name="geomType"> <xs:sequence> <xs:element ref="gml:polygonProperty" minOccurs="0"/> </xs:sequence> </xs:complexType> */ geomQuery = describeFeatureTypeQueryManager.GetXPathQueryManagerInContext( describeFeatureTypeQueryManager.Compile(_TextResources.XPATH_GEOMETRYELEMENTCOMPLEXTYPE_BYELEMREFQUERY)); if (geomQuery != null) { /* Ask for the name of the complextype - use the local context*/ geomComplexTypeName = geomQuery.GetValueFromNode(geomQuery.Compile(_TextResources.XPATH_NAMEATTRIBUTEQUERY)); if (geomComplexTypeName != null) { /* Ask for the name of an element with a complextype of 'geomComplexType' - use the global context */ geomName = describeFeatureTypeQueryManager.GetValueFromNode(describeFeatureTypeQueryManager.Compile( _TextResources.XPATH_GEOMETRY_ELEMREF_GEOMNAMEQUERY), new DictionaryEntry[] { new DictionaryEntry("_param1", _FeatureTypeInfo.FeatureTypeNamespace), new DictionaryEntry("_param2", geomComplexTypeName)}); } else { /* The geometry element must be an ancestor, if we found an anonymous complextype */ /* Ask for the element hosting the anonymous complextype - use the global context */ /* example: <xs:element name ="SHAPE"> <xs:complexType> <xs:sequence> <xs:element ref="gml:lineStringProperty" minOccurs="0"/> </xs:sequence> </xs:complexType> </xs:element> */ geomName = describeFeatureTypeQueryManager.GetValueFromNode(describeFeatureTypeQueryManager.Compile(_TextResources.XPATH_GEOMETRY_ELEMREF_GEOMNAMEQUERY_ANONYMOUSTYPE)); } /* Just, if not set manually... */ if (geomType == null) { /* Ask for the 'ref'-attribute - use the local context */ if ((geomType = geomQuery.GetValueFromNode(geomQuery.Compile(_TextResources.XPATH_GEOMETRY_ELEMREF_GMLELEMENTQUERY))) != null) { switch (geomType) { case "gml:pointProperty": geomType = "PointPropertyType"; break; case "gml:lineStringProperty": geomType = "LineStringPropertyType"; break; case "gml:curveProperty": geomType = "CurvePropertyType"; break; case "gml:polygonProperty": geomType = "PolygonPropertyType"; break; case "gml:surfaceProperty": geomType = "SurfacePropertyType"; break; case "gml:multiPointProperty": geomType = "MultiPointPropertyType"; break; case "gml:multiLineStringProperty": geomType = "MultiLineStringPropertyType"; break; case "gml:multiCurveProperty": geomType = "MultiCurvePropertyType"; break; case "gml:multiPolygonProperty": geomType = "MultiPolygonPropertyType"; break; case "gml:multiSurfaceProperty": geomType = "MultiSurfacePropertyType"; break; // e.g. 'gml:_geometryProperty' default: break; } } } } } if (geomName == null) /* Default value for geometry column = geom */ geomName = "geom"; if (geomType == null) /* Set geomType to an empty string in order to avoid exceptions. The geometry type is not necessary by all means - it can be detected in 'GetFeature' response too.. */ geomType = string.Empty; /* Remove prefix */ if (geomType.Contains(":")) geomType = geomType.Substring(geomType.IndexOf(":") + 1); WfsFeatureTypeInfo.GeometryInfo geomInfo = new WfsFeatureTypeInfo.GeometryInfo(); geomInfo._GeometryName = geomName; geomInfo._GeometryType = geomType; _FeatureTypeInfo.Geometry = geomInfo; } finally { _HttpClientUtil.Close(); } }
private string ConvertDecimalUserInputToLocalizedString(string userInput) { System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); string chunkSizeString = userInput; if (chunkSizeString.Contains(".") == true && chunkSizeString.Contains(nfi.CurrencyDecimalSeparator) == false) chunkSizeString = chunkSizeString.Replace(".", nfi.CurrencyDecimalSeparator); return chunkSizeString; }
protected bool readObjectsLoop(StreamReader rdr, int ver_major, int ver_minor, TreeNode parent) { string str; while (!rdr.EndOfStream) { str = rdr.ReadLine(); if (rdr.EndOfStream) return true; if (str.Length < 2) continue; string rest = str.Substring(2); //TODO check string[] typename = new string[2]; int idx = rest.IndexOf(' '); typename[0] = rest.Substring(0, idx); typename[1] = rest.Substring(idx+1); //ITEM if (typename[0] == "Item") { Item it = new Item(mAdv); it.Name = typename[1]; int numStates = STATES_MAX; int delim = 2; if (ver_major == 2 || (ver_major == 3 && ver_minor == 0)) { numStates = 1; delim = 1; } for (int state = 0; state < numStates; ++state) { ItemState ist; ist.frames = new System.Collections.ArrayList(); ist.scripts = new System.Collections.ArrayList(); for (int frames = 0; frames < FRAMES_MAX; ++frames) { str = rdr.ReadLine(); if (str.Length > 0) { if (delim == 2) { string[] split = str.Split(';'); ist.frames.Add(split[0]); if (split.Length > 1) ist.scripts.Add(split[1].Replace('\xaf', ';')); else ist.scripts.Add(""); } else { ist.frames.Add(str.Substring(0, str.Length + 1 - delim)); ist.scripts.Add(""); } } } str = rdr.ReadLine(); ist.fpsDivider = Convert.ToInt32(str); it.Add(ist); } if (ver_major == 2 || (ver_major == 3 && ver_minor == 0)) { for (int i = 1; i < STATES_MAX; ++i) { ItemState ist; ist.frames = new System.Collections.ArrayList(); ist.scripts = new System.Collections.ArrayList(); ist.fpsDivider = 20; it.Add(ist); } } mAdv.addItem(it); } //OBJECT else if (typename[0] == "Object") { AdvObject obj = mAdv.getObject(typename[1]); if (obj == null) { obj = new AdvObject(mAdv); obj.Name = typename[1]; mAdv.addObject(obj); } str = rdr.ReadLine(); int x = Convert.ToInt32(str); str = rdr.ReadLine(); int y = Convert.ToInt32(str); obj.setSize(0, new Vec2i(x, y)); str = rdr.ReadLine(); x = Convert.ToInt32(str); obj.Lighten = x != 0; for (int state = 0; state < STATES_MAX; ++state) { ObjectState os = new ObjectState(); os.fpsDivider = readExtendedFrames(rdr, os.frames); obj.Add(os); } } //CHARACTER else if (typename[0] == "Character") { AdvCharacter chr = new AdvCharacter(mAdv); chr.Name = typename[1]; str = rdr.ReadLine(); chr.TextColor = Convert.ToUInt32(str); chr.WalkSpeed = Convert.ToInt32(rdr.ReadLine()); if (ver_major > 0) { int tmp = Convert.ToInt32(rdr.ReadLine()); chr.NoZoom = tmp != 0; if (ver_major > 3 || (ver_major == 3 && ver_minor > 0)) { tmp = Convert.ToInt32(rdr.ReadLine()); chr.RealLeftAnimations = tmp != 0; } tmp = Convert.ToInt32(rdr.ReadLine()); chr.MemoryReistent = tmp != 0; tmp = Convert.ToInt32(rdr.ReadLine()); chr.Ghost = tmp != 0; chr.Walksound = rdr.ReadLine(); } if (ver_major >= 3) { str = rdr.ReadLine(); string[] names = str.Split(';'); for (int i = 0; i < names.Length - 1; ++i) { chr.setStateName(16 + i, names[i]); } } else { for (int i = 0; i < 20; ++i) chr.setStateName(16 + i, ""); } if (ver_major > 0) { chr.Font = Convert.ToInt32(rdr.ReadLine()); chr.Zoom = Convert.ToInt32(rdr.ReadLine()); } else chr.Zoom = 100; for (int state = 0; state < CHAR_STATES_MAX; ++state) { CharacterState cs = new CharacterState(); cs.size.x = Convert.ToInt32(rdr.ReadLine()); cs.size.y = Convert.ToInt32(rdr.ReadLine()); cs.basepoint.x = Convert.ToInt32(rdr.ReadLine()); cs.basepoint.y = Convert.ToInt32(rdr.ReadLine()); cs.fpsDivider = readExtendedFrames(rdr, cs.frames); chr.Add(cs); } mAdv.addCharacter(chr); } //CHARACTER INSTANCE else if (typename[0] == "Rcharacter") { string chr = rdr.ReadLine(); CharacterInstance charinst = new CharacterInstance(mAdv.getCharacter(chr), mAdv); if (charinst.Character == null) throw new UnexpectedValueException("No character for character instance found"); charinst.Name = typename[1]; charinst.Room = rdr.ReadLine(); Vec2i pos; pos.x = Convert.ToInt32(rdr.ReadLine()); pos.y = Convert.ToInt32(rdr.ReadLine()); charinst.RawPosition = pos; charinst.LookDir = Convert.ToInt32(rdr.ReadLine()); charinst.Unmovable = Convert.ToInt32(rdr.ReadLine()) == 0; charinst.Locked = Convert.ToInt32(rdr.ReadLine()) != 0; if (!mAdv.CharacterInstances.ContainsKey(charinst.Room.ToLower())) { mAdv.CharacterInstances[charinst.Room.ToLower()] = new System.Collections.ArrayList(); } mAdv.CharacterInstances[charinst.Room.ToLower()].Add(charinst); } //ROOM else if (typename[0] == "Room") { Room room = new Room(); room.Data = mAdv; room.Name = typename[1]; room.Size.x = Convert.ToInt32(rdr.ReadLine()); room.Size.y = Convert.ToInt32(rdr.ReadLine()); room.ScrollOffset.x = Convert.ToInt32(rdr.ReadLine()); room.ScrollOffset.y = Convert.ToInt32(rdr.ReadLine()); room.Depthmap.x = Convert.ToInt32(rdr.ReadLine()); room.Depthmap.y = Convert.ToInt32(rdr.ReadLine()); room.Zoom = Convert.ToInt32(rdr.ReadLine()); room.Background = rdr.ReadLine(); room.ParallaxBackground = rdr.ReadLine(); room.FXShapes = new System.Collections.ArrayList(); if (ver_major >= 3) { int tmp = Convert.ToInt32(rdr.ReadLine()); room.DoubleWalkmap = tmp != 0; } else { room.DoubleWalkmap = false; } if (ver_major > 3 || (ver_major == 3 && ver_minor >= 5)) { str = rdr.ReadLine(); string[] col = str.Split(';'); room.Lighting = Color.FromArgb(Convert.ToInt32(col[0]), Convert.ToInt32(col[1]), Convert.ToInt32(col[2])); } else room.Lighting = Color.FromArgb(255, 255, 255); if (ver_major >= 3 || (ver_major == 2 && ver_minor >= 8)) { for (int i = 0; i < FXSHAPES_MAX; ++i) { FxShape shape = new FxShape(); str = rdr.ReadLine(); string[] split = str.Split(';'); shape.Active = Convert.ToInt32(split[0]) != 0; shape.DependingOnRoomPosition = Convert.ToInt32(split[1]) != 0; shape.Effect = (FxShape.FxEffect)Convert.ToInt32(rdr.ReadLine()); shape.Room = rdr.ReadLine(); shape.Depth = Convert.ToInt32(rdr.ReadLine()); shape.MirrorOffset.x = Convert.ToInt32(rdr.ReadLine()); shape.MirrorOffset.y = Convert.ToInt32(rdr.ReadLine()); shape.Strength = Convert.ToInt32(rdr.ReadLine()); str = rdr.ReadLine(); split = str.Split(';'); for (int pos = 0; pos < 4; ++pos) { shape.Positions[pos].x = Convert.ToInt32(split[2 * pos]); shape.Positions[pos].y = Convert.ToInt32(split[2 * pos + 1]); } room.FXShapes.Add(shape); } } else { for (int i = 0; i < FXSHAPES_MAX; ++i) { FxShape fs = new FxShape(i); room.FXShapes.Add(fs); } } //inventory room.HasInventory = Convert.ToInt32(rdr.ReadLine()) != 0; str = rdr.ReadLine(); string[] inventory = str.Split(';'); room.InvPos.x = Convert.ToInt32(inventory[0]); room.InvPos.y = Convert.ToInt32(inventory[1]); room.InvSize.x = Convert.ToInt32(inventory[2]); room.InvSize.y = Convert.ToInt32(inventory[3]); if (ver_major < 3) { if (room.InvSize.x == 0 || room.InvSize.y == 0) room.HasInventory = false; else room.HasInventory = true; } System.Globalization.NumberFormatInfo info = new System.Globalization.NumberFormatInfo(); info.NumberDecimalSeparator = ","; try { room.InvScale.x = Single.Parse(inventory[4], info); room.InvScale.y = Single.Parse(inventory[5], info); } catch (Exception) { info.NumberDecimalSeparator = "."; room.InvScale.x = Single.Parse(inventory[4], info); room.InvScale.y = Single.Parse(inventory[5], info); } if (ver_major > 3 || (ver_major == 3 && ver_minor >= 5)){ room.InvSpacing = Convert.ToInt32(inventory[6]); } else room.InvSpacing = 10; //walkmap str = rdr.ReadLine(); int walkmapX = 32; int walkGridSize = mAdv.Settings.Resolution.x / walkmapX; int walkmapY = mAdv.Settings.Resolution.y / walkGridSize; walkmapX *= 3; walkmapY *= 2; int walkmapXOut = walkmapX * 2; int walkmapYOut = walkmapY * 2; if (ver_major >= 3) { walkmapX *= 2; walkmapY *= 2; } room.Walkmap = new Room.WalkMapEntry[walkmapXOut, walkmapYOut]; for (int i = 0; i < walkmapX * walkmapY; ++i) { int x = i / walkmapY; int y = i % walkmapY; room.Walkmap[x, y].isFree = str[2 * i] != '1'; room.Walkmap[x, y].hasScript = str[2 * i + 1] == '1'; } if (mAdv.CharacterInstances.ContainsKey(room.Name.ToLower())) room.Characters = mAdv.CharacterInstances[room.Name.ToLower()]; mAdv.addRoom(room); mLastRoom = room; } //OBJECT INSTANCE else if (typename[0] == "Roomobject") { string obj = rdr.ReadLine(); AdvObject newobj = mAdv.getObject(obj); if (newobj == null) { //this happens during room import newobj = new AdvObject(mAdv); newobj.Name = obj; mAdv.addObject(newobj); //auto add objects if (parent != null) { TreeNode tno = new TreeNode(obj); tno.Tag = ResourceID.OBJECT; tno.ImageIndex = Utilities.ResourceIDToImageIndex((ResourceID)tno.Tag); tno.SelectedImageIndex = tno.ImageIndex; parent.Nodes.Add(tno); } } ObjectInstance objinst = new ObjectInstance(mAdv.getObject(obj), mAdv); objinst.Name = typename[1]; objinst.Position.x = Convert.ToInt32(rdr.ReadLine()); objinst.Position.y = Convert.ToInt32(rdr.ReadLine()); objinst.State = Convert.ToInt32(rdr.ReadLine()); objinst.Layer = Convert.ToInt32(rdr.ReadLine()); objinst.Depth = Convert.ToInt32(rdr.ReadLine())*2; if (ver_major > 3 || (ver_major == 3 && ver_minor >= 5)) { objinst.Depth = Convert.ToInt32(rdr.ReadLine()); } objinst.Locked = Convert.ToInt32(rdr.ReadLine()) != 0; mLastRoom.Objects.Add(objinst); } } return true; }
/// <summary> /// String to float array /// </summary> /// <param name="text">String</param> /// <returns>Array</returns> public static float[] StringToFloat(string text) { System.Globalization.NumberFormatInfo info = new System.Globalization.NumberFormatInfo(); info.NumberDecimalSeparator = "."; var parts = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); return (from p in parts select float.Parse(p, info)).ToArray(); }
private static ScanResult SnipeScanForPokemon(Location location) { var formatter = new System.Globalization.NumberFormatInfo() { NumberDecimalSeparator = "." }; var uri = $"https://pokevision.com/map/data/{location.Latitude.ToString(formatter)}/{location.Longitude.ToString(formatter)}"; ScanResult scanResult; try { var request = WebRequest.CreateHttp(uri); request.Accept = "application/json"; request.Method = "GET"; request.Timeout = 1000; var resp = request.GetResponse(); var reader = new StreamReader(resp.GetResponseStream()); scanResult = JsonConvert.DeserializeObject<ScanResult>(reader.ReadToEnd()); } catch (Exception) { scanResult = new ScanResult() { status = "fail", pokemon = new List<PokemonLocation>() }; } return scanResult; }
private void setLabels() { switch (vyjimecnost) { case 1: vyjimecnostL.Text = "Výjimečné vlastnosti"; break; case 2: vyjimecnostL.Text = "Kombinace vlastností a zázemí"; break; case 3: vyjimecnostL.Text = "Dobré zázemí"; break; } boduZazemiL.Text = boduLeft.ToString(); PuvodBody.Text = body[0].ToString(); MajetekBody.Text = body[1].ToString(); DovednostiBody.Text = body[2].ToString(); System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo(); nfi.NumberGroupSeparator = " "; puvodL.Text = puvody[body[0]]; majetekL.Text = majetky[body[1]].ToString() + " zlatých"; fyzL.Text = dovednosti[body[2]][0].ToString(); psyL.Text = dovednosti[body[2]][1].ToString(); kombL.Text = dovednosti[body[2]][2].ToString(); }
private Dictionary<Hashtable, bool> seenHashtables; //for serialize (to infinte prevent loops) #endregion Fields #region Constructors public Serializer() { this.nfi = new System.Globalization.NumberFormatInfo(); this.nfi.NumberGroupSeparator = ""; this.nfi.NumberDecimalSeparator = "."; }
public HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings) { reader.Close(); // Initialize the import // Load the ase file content // Create a List for all meshes // Create a list for the current-mesh strands string[] aseContent = File.ReadAllLines(path); List<HairMesh> hairMeshes = new List<HairMesh>(); List<HairStrand> currentStrands = new List<HairStrand>(); // Init "state"-variables int currentStrand = 0; int currentHairId = -1; float texcoordMultiplier = 0; // Now the hard part begins... for (int i = 0; i < aseContent.Length; i++) { string[] tokens = aseContent[i].Split('\t'); if (aseContent[i].Contains("*SHAPE_LINECOUNT")) { tokens = tokens[1].Split(' '); } else if (aseContent[i].Contains("SHAPE_LINE")) { tokens = tokens[1].Split(' '); } if (tokens.Length >= 2) { if (tokens[0] == "*SHAPE_LINECOUNT") { if (currentStrand > 0) { // Start parsing next mesh after flushing the current strands buffer currentHairId++; currentStrand = 0; // Add to mesh list / flush current strands buffer HairMesh hairMesh = new HairMesh(); foreach (HairStrand strand in currentStrands) { hairMesh.strands.Add(strand); } hairMeshes.Add(hairMesh); // Clear current strands currentStrands.Clear(); texcoordMultiplier = 1.0f / (float)int.Parse(tokens[1]); } } else if (tokens[0] == "*SHAPE_LINE") { HairStrand strand = new HairStrand(); strand.isGuidanceStrand = true; string[] vertexCountTokens = aseContent[i + 1].Split(' '); // Parse the current line int vertexCount = int.Parse(vertexCountTokens[1]); // Parse vertices for (int j = 0; j < vertexCount; j++) { string[] vertexTokens = aseContent[i + 2 + j].Replace('.', ',').Split('\t'); if (vertexTokens[2] == "*SHAPE_VERTEX_INTERP") continue; System.Globalization.NumberFormatInfo nf = new System.Globalization.NumberFormatInfo() { NumberGroupSeparator = "." }; vertexTokens[4] = vertexTokens[4].Replace(',', '.'); vertexTokens[5] = vertexTokens[5].Replace(',', '.'); vertexTokens[6] = vertexTokens[6].Replace(',', '.'); Vector3 position = new Vector3(float.Parse(vertexTokens[4], nf), float.Parse(vertexTokens[6], nf), float.Parse(vertexTokens[5], nf)); position = Vector3.Multiply(position, importSettings.scale); HairStrandVertex v = new HairStrandVertex(position, Vector3.Zero, Vector4.Zero); if (strand.vertices.Count == 0) v.isMovable = false; strand.vertices.Add(v); } currentStrands.Add(strand); // Increment file-line-pointer i = i + 1 + vertexCount; currentStrand++; } } } // Get last mesh HairMesh lastMesh = new HairMesh(); lastMesh.strands.AddRange(currentStrands); hairMeshes.Add(lastMesh); return hairMeshes.ToArray(); }