/// <summary> /// Constructs a <see cref="NumericConfig"/> object. /// </summary> /// <param name="precisionStep">the precision used to index the numeric values</param> /// <param name="format">the <see cref="NumberFormat"/> used to parse a <see cref="string"/> to an <see cref="object"/> representing a .NET numeric type.</param> /// <param name="type">the numeric type used to index the numeric values</param> /// <seealso cref="NumericConfig.PrecisionStep"/> /// <seealso cref="NumericConfig.NumberFormat"/> /// <seealso cref="Type"/> public NumericConfig(int precisionStep, NumberFormat format, NumericType type) { PrecisionStep = precisionStep; NumberFormat = format; Type = type; }
/// <summary> /// Determines the cell XF entries in a XML node of the style document /// </summary> /// <param name="node">Cell XF root node</param> private void GetCellXfs(XmlNode node) { try { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName.Equals("xf", StringComparison.InvariantCultureIgnoreCase)) { Style style = new Style(); int id = int.Parse(ReaderUtils.GetAttribute("numFmtId", childNode)); NumberFormat format = StyleReaderContainer.GetNumberFormat(id, true); if (format == null) { NumberFormat.FormatNumber formatNumber; NumberFormat.TryParseFormatNumber(id, out formatNumber); // Validity is neglected here to prevent unhandled crashes. If invalid, the format will be declared as 'none' // Invalid values should not occur at all (malformed Excel files). //Undefined values may occur if the file was saved by an Excel version that has implemented yet unknown format numbers (undefined in NanoXLSX) format = new NumberFormat(); format.Number = formatNumber; format.InternalID = StyleReaderContainer.GetNextNumberFormatId(); StyleReaderContainer.AddStyleComponent(format); } // TODO: Implement other style information style.CurrentNumberFormat = format; style.InternalID = StyleReaderContainer.GetNextStyleId(); StyleReaderContainer.AddStyleComponent(style); } } } catch (Exception ex) { throw new IOException("XMLStreamException", "The style information could not be resolved. Please see the inner exception:", ex); } }
public virtual string GetDescription(int numDigits) { NumberFormat nf = NumberFormat.GetNumberInstance(); nf.SetMaximumFractionDigits(numDigits); StringBuilder sb = new StringBuilder(); sb.Append("--- Accuracy Stats ---").Append('\n'); sb.Append("accuracy: ").Append(nf.Format(accuracy)).Append('\n'); sb.Append("optimal fn accuracy: ").Append(nf.Format(optAccuracy)).Append('\n'); sb.Append("confidence weighted accuracy :").Append(nf.Format(confWeightedAccuracy)).Append('\n'); sb.Append("optimal confidence weighted accuracy: ").Append(nf.Format(optConfWeightedAccuracy)).Append('\n'); sb.Append("log-likelihood: ").Append(logLikelihood).Append('\n'); if (saveFile != null) { string f = saveFile + '-' + saveIndex; sb.Append("saving accuracy info to ").Append(f).Append(".accuracy\n"); StringUtils.PrintToFile(f + ".accuracy", ToStringArr(accrecall)); sb.Append("saving optimal accuracy info to ").Append(f).Append(".optimal_accuracy\n"); StringUtils.PrintToFile(f + ".optimal_accuracy", ToStringArr(optaccrecall)); saveIndex++; } //sb.append("accuracy coverage: ").append(toStringArr(accrecall)).append("\n"); //sb.append("optimal accuracy coverage: ").append(toStringArr(optaccrecall)); return(sb.ToString()); }
private void SetString() { var amount = (long)numAmount.Value; var txt = NumberFormat.ToFarsi(amount); lblAmount.Text = txt; }
public void VerifyFormatOfBooleanParameterType() { var booleanParameterType = new BooleanParameterType(); var format = NumberFormat.Format(booleanParameterType); Assert.AreEqual("@", format); }
internal override NumberFormat CreateInstance(IBM.ICU.Util.ULocale desiredLocale, int choice) { // use service cache // if (service.isDefault()) { // return NumberFormat.createInstance(desiredLocale, choice); // } ULocale[] actualLoc = new ULocale[1]; if (desiredLocale.Equals(IBM.ICU.Util.ULocale.ROOT)) { desiredLocale = IBM.ICU.Util.ULocale.ROOT; } NumberFormat fmt = (NumberFormat)service.Get(desiredLocale, choice, actualLoc); if (fmt == null) { throw new MissingManifestResourceException("Unable to construct NumberFormat"); } fmt = (NumberFormat)fmt.Clone(); ULocale uloc = actualLoc[0]; fmt.SetLocale(uloc, uloc); // services make no distinction between // actual & valid return(fmt); }
public void VerifyFormatOfDateTimeParameterType() { var dateTimeParameterType = new DateTimeParameterType(); var format = NumberFormat.Format(dateTimeParameterType); Assert.AreEqual("yyyy-mm-dd hh:mm:ss", format); }
public void VerifyFormatOfCompoundParameterType() { var compoundParameterType = new CompoundParameterType(); var format = NumberFormat.Format(compoundParameterType); Assert.AreEqual("@", format); }
/// <summary> /// Creates an identifier for an ETD option instrument. /// <para> /// This takes into account the expiry of the underlying instrument. If the underlying expiry /// is the same as the expiry of the option, the identifier is the same as the normal one. /// Otherwise, the underlying expiry is added after the option expiry. For example: /// {@code 'OG-ETD~O-ECAG-OGBS-201706-P1.50-U201709'}. /// /// </para> /// </summary> /// <param name="exchangeId"> the MIC code of the exchange where the instruments are traded </param> /// <param name="contractCode"> the code supplied by the exchange for use in clearing and margining, such as in SPAN </param> /// <param name="expiryMonth"> the month of expiry </param> /// <param name="variant"> the variant of the ETD, such as 'Monthly', 'Weekly, 'Daily' or 'Flex' </param> /// <param name="version"> the non-negative version, zero by default </param> /// <param name="putCall"> the Put/Call flag </param> /// <param name="strikePrice"> the strike price </param> /// <param name="underlyingExpiryMonth"> the expiry of the underlying instrument, such as a future, may be null </param> /// <returns> the identifier </returns> public static SecurityId optionId(ExchangeId exchangeId, EtdContractCode contractCode, YearMonth expiryMonth, EtdVariant variant, int version, PutCall putCall, double strikePrice, YearMonth underlyingExpiryMonth) { ArgChecker.notNull(exchangeId, "exchangeId"); ArgChecker.notNull(contractCode, "contractCode"); ArgChecker.notNull(expiryMonth, "expiryMonth"); ArgChecker.notNull(variant, "variant"); ArgChecker.notNull(putCall, "putCall"); string putCallStr = putCall == PutCall.PUT ? "P" : "C"; string versionCode = version > 0 ? "V" + version + SEPARATOR : ""; NumberFormat f = NumberFormat.getIntegerInstance(Locale.ENGLISH); f.GroupingUsed = false; f.MaximumFractionDigits = 8; string strikeStr = f.format(strikePrice).replace('-', 'M'); string underlying = ""; if (underlyingExpiryMonth != null && !underlyingExpiryMonth.Equals(expiryMonth)) { underlying = SEPARATOR + "U" + underlyingExpiryMonth.format(YM_FORMAT); } string id = (new StringBuilder(40)).Append(OPT_PREFIX).Append(exchangeId).Append(SEPARATOR).Append(contractCode).Append(SEPARATOR).Append(expiryMonth.format(YM_FORMAT)).Append(variant.Code).Append(SEPARATOR).Append(versionCode).Append(putCallStr).Append(strikeStr).Append(underlying).ToString(); return(SecurityId.of(ETD_SCHEME, id)); }
public void Formatting(string widget = "") { if (widget == "Sparkline") { NumberFormat.SelectDropdown("Time"); } NumberFormat.SelectDropdown("Number"); Decimal.SelectDropdown("3"); ShowCommas.Clicks(); if (widget == "" || widget == "Heatmap") { AddCondition.Clicks(); AddConditionTo.EnterText("10000"); AddConditionFrom.EnterText("90000"); ColorSelect.Clicks(); SelectColor.Clicks(); } }
public void VerifyFormatOfEnumerationParameterType() { var enumerationParameterType = new EnumerationParameterType(); var format = NumberFormat.Format(enumerationParameterType); Assert.AreEqual("@", format); }
public void TestGuess(string input, string expectedDecimalSeparator, string expectedGroupSeparator) { var nf = NumberFormat.GuessNumberFormat(input); Check.That(nf.NumberDecimalSeparator).IsEqualTo(expectedDecimalSeparator); Check.That(nf.NumberGroupSeparator).IsEqualTo(expectedGroupSeparator); }
internal NumberFormatInfo(NumberFormat numberFormat) { this.numberFormat = numberFormat; currencyGroupSizes = new[] { 3 }; numberGroupSizes = new[] { 3 }; percentGroupSizes = new[] { 3 }; }
private static IEnumerator <RantAction> NumberFormatRange(Sandbox sb, [RantDescription("The number format to use.")] NumberFormat format, [RantDescription("The pattern to run.")] RantAction rangeAction) { var oldFmtMap = new Dictionary <OutputChain, NumberFormat>(); sb.Output.Do(chain => { oldFmtMap[chain] = chain.Last.NumberFormatter.NumberFormat; chain.Last.NumberFormatter.NumberFormat = format; }); yield return(rangeAction); NumberFormat fmt; sb.Output.Do(chain => { if (!oldFmtMap.TryGetValue(chain, out fmt)) { return; } chain.Last.NumberFormatter.NumberFormat = fmt; }); }
static void Main(string[] args) { var format = new NumberFormat("[<=6e+3]# ??/\"a\"[Blue]?\"a\"0\"a\""); var result = format.Format(0.12, CultureInfo.InvariantCulture); Console.WriteLine("\"" + result.ToString() + "\""); }
public virtual string ToString(NumberFormat nf) { StringBuilder sb = new StringBuilder(); sb.Append("{"); IList <E> list = new List <E>(map.Keys); try { (IList)list.Sort(); } catch (Exception) { } // see if it can be sorted for (IEnumerator <E> iter = list.GetEnumerator(); iter.MoveNext();) { object key = iter.Current; MutableInteger d = map[key]; sb.Append(key + "="); sb.Append(nf.Format(d)); if (iter.MoveNext()) { sb.Append(", "); } } sb.Append("}"); return(sb.ToString()); }
public override void complete() { NumberFormat nfMegabyte = NumberFormat.Instance; NumberFormat nfCounts = NumberFormat.Instance; nfCounts.GroupingUsed = true; nfMegabyte.MaximumFractionDigits = 2; LOGGER.info("completing read..."); this.tileBasedGeoObjectStore.complete(); LOGGER.info("start writing file..."); try { if (this.configuration.OutputFile.exists()) { LOGGER.info("overwriting file " + this.configuration.OutputFile.AbsolutePath); this.configuration.OutputFile.delete(); } MapFileWriter.writeFile(this.configuration, this.tileBasedGeoObjectStore); } catch (IOException e) { LOGGER.log(Level.SEVERE, "error while writing file", e); } LOGGER.info("finished..."); LOGGER.fine("total processed nodes: " + nfCounts.format(this.amountOfNodesProcessed)); LOGGER.fine("total processed ways: " + nfCounts.format(this.amountOfWaysProcessed)); LOGGER.fine("total processed relations: " + nfCounts.format(this.amountOfRelationsProcessed)); LOGGER.info("estimated memory consumption: " + nfMegabyte.format(+((Runtime.Runtime.totalMemory() - Runtime.Runtime.freeMemory()) / Math.Pow(1024, 2))) + "MB"); }
public ElapsedTimer(String pattern) { this.startTime = DateTime.Now.Millisecond; this.myDurationFormat = null; this.myMsgFormat = null; myMsgFormat = new MessageFormat(pattern); }
string GenerateStyleTemplate() { var r = new StringBuilder(); r.AppendLine(@"<Style ss:ID=""[#Style.ID#]"">"); r.AddFormattedLine(@"<Alignment ss:Horizontal=""{0}"" ss:Vertical=""{1}"" ss:Rotate=""{2}""{3}/>", Alignment, VerticalAlignment, GetCellRotation(), " ss:WrapText=\"1\"".OnlyWhen(WrapText)); r.AddFormattedLine(@"<Font ss:FontName=""{0}"" x:Family=""Swiss"" ss:Size=""{1}"" ss:Color=""{2}"" ss:Bold=""{3}"" ss:Italic=""{4}"" />", FontName, FontSize, ForeColor, Bold ? 1 : 0, Italic ? 1 : 0); if (BackgroundColor.HasValue() && BackgroundColor.ToUpper() != "#FFFFFF") { r.AddFormattedLine(@"<Interior ss:Color=""{0}"" ss:Pattern=""Solid""/>", BackgroundColor); } if (BorderWidth > 0) { r.AddFormattedLine(@"<Borders> <Border ss:Position=""Bottom"" ss:LineStyle=""Continuous"" ss:Weight=""{1}"" ss:Color=""{0}""/> <Border ss:Position=""Left"" ss:LineStyle=""Continuous"" ss:Weight=""{1}"" ss:Color=""{0}""/> <Border ss:Position=""Right"" ss:LineStyle=""Continuous"" ss:Weight=""{1}"" ss:Color=""{0}""/> <Border ss:Position=""Top"" ss:LineStyle=""Continuous"" ss:Weight=""{1}"" ss:Color=""{0}""/> </Borders>", BorderColor, BorderWidth); } if (NumberFormat.HasValue()) { r.AddFormattedLine(@"<NumberFormat ss:Format=""{0}"" />", NumberFormat.HtmlEncode()); } r.AppendLine(@"</Style>"); return(r.ToString()); }
internal override NumberFormat CreateInstance(UCultureInfo desiredLocale, NumberFormatStyle choice) { // use service cache // if (service.isDefault()) { // return NumberFormat.createInstance(desiredLocale, choice); // } NumberFormat fmt = (NumberFormat)service.Get(desiredLocale, (int)choice, out UCultureInfo actualLoc); if (fmt == null) { throw new MissingManifestResourceException("Unable to construct NumberFormat"); } fmt = (NumberFormat)fmt.Clone(); // ICU4N TODO: Currency //// If we are creating a currency type formatter, then we may have to set the currency //// explicitly, since the actualLoc may be different than the desiredLocale //if (choice == NumberFormat.CURRENCYSTYLE || // choice == NumberFormat.ISOCURRENCYSTYLE || // choice == NumberFormat.PLURALCURRENCYSTYLE) //{ // fmt.SetCurrency(Currency.GetInstance(desiredLocale)); //} UCultureInfo uloc = actualLoc; fmt.SetCulture(uloc, uloc); // services make no distinction between actual & valid return(fmt); }
public ElapsedTimer(NumberFormat aNumFmt) { this.startTime = DateTime.Now.Millisecond; this.myDurationFormat = null; this.myMsgFormat = null; myDurationFormat = aNumFmt; }
/// <summary> /// Sets up the operation using the given configuration by setting up the /// number of operations to perform (and how many are left) and setting up the /// operation objects to be used throughout selection. /// </summary> /// <param name="cfg">ConfigExtractor.</param> private void ConfigureOperations(ConfigExtractor cfg) { operations = new SortedDictionary <Constants.OperationType, WeightSelector.OperationInfo >(); IDictionary <Constants.OperationType, OperationData> opinfo = cfg.GetOperations(); int totalAm = cfg.GetOpCount(); int opsLeft = totalAm; NumberFormat formatter = Formatter.GetPercentFormatter(); foreach (Constants.OperationType type in opinfo.Keys) { OperationData opData = opinfo[type]; WeightSelector.OperationInfo info = new WeightSelector.OperationInfo(); info.distribution = opData.GetDistribution(); int amLeft = DetermineHowMany(totalAm, opData, type); opsLeft -= amLeft; Log.Info(type.ToString() + " has " + amLeft + " initial operations out of " + totalAm + " for its ratio " + formatter.Format(opData.GetPercent())); info.amountLeft = amLeft; Operation op = factory.GetOperation(type); // wrap operation in finalizer so that amount left gets decrements when // its done if (op != null) { ObserveableOp.Observer fn = new _Observer_138(this, type); info.operation = new ObserveableOp(op, fn); operations[type] = info; } } if (opsLeft > 0) { Log.Info(opsLeft + " left over operations found (due to inability to support partial operations)" ); } }
/// <summary>Returns a String summarizing recall that will print nicely.</summary> public virtual string GetRecallDescription(int numDigits) { NumberFormat nf = NumberFormat.GetNumberInstance(); nf.SetMaximumFractionDigits(numDigits); return(nf.Format(GetRecall()) + " (" + tpCount + "/" + (tpCount + fnCount) + ")"); }
void onCalculateBtnClick(object sender, EventArgs e) { if (billAmount.Text.Length > 0) { double bill = 0; bool isValid = double.TryParse(billAmount.Text.ToString(), out bill); //if (!isValid) // return; //double bill = double.Parse(billAmount.Text); NumberFormat nf = NumberFormat.GetCurrencyInstance(Android.Icu.Util.ULocale.Default); var parsed = nf.Parse(billAmount.Text.ToString()); var myVal = parsed.DoubleValue(); if (bill > 0.0) { double tip = bill * 15 / 100; double total = bill + tip; tipVal.Text = tip.ToString("N"); totalVal.Text = total.ToString("N"); } else { tipVal.Text = "0.00"; totalVal.Text = "0.00"; } } else { tipVal.Text = "0.00"; totalVal.Text = "0.00"; } }
/** * Sets the format for the number based on the Excel spreadsheets' format. * This is called from SheetImpl when it has been definitely established * that this cell is a number and not a date * * @param f the format */ public void setNumberFormat(NumberFormat f) { if (f != null) { format = f; } }
protected static string BuildDefinition(Requirement requirement, NumberFormat numberFormat) { var builder = new StringBuilder(); switch (requirement.Type) { case RequirementType.AddHits: builder.Append("AddHits "); break; case RequirementType.AndNext: builder.Append("AndNext "); break; } requirement.AppendString(builder, numberFormat); if (requirement.Type == RequirementType.SubSource) { // change " - " to "-" and add " + " to the end builder.Remove(0, 1); builder.Remove(1, 1); builder.Append(" + "); } return(builder.ToString()); }
public virtual string GetF1Description(int numDigits, L label) { NumberFormat nf = NumberFormat.GetNumberInstance(); nf.SetMaximumFractionDigits(numDigits); return(nf.Format(GetFMeasure(label))); }
static EventLogger() { TIME_FORMAT = NumberFormat.GetInstance(Locale.Us); TIME_FORMAT.MinimumFractionDigits = 2; TIME_FORMAT.MaximumFractionDigits = 2; TIME_FORMAT.GroupingUsed = false; }
public ElapsedTimer(MessageFormat aMsgFmt) { this.startTime = DateTime.Now.Millisecond; this.myDurationFormat = null; this.myMsgFormat = null; myMsgFormat = aMsgFmt; }
public virtual string ToCSVString(NumberFormat nf) { IList <K1> firstKeys = new List <K1>(FirstKeySet()); IList <K2> secondKeys = new List <K2>(SecondKeySet()); (IList <IComparable>)firstKeys.Sort(); (IList <IComparable>)secondKeys.Sort(); StringBuilder b = new StringBuilder(); string[] headerRow = new string[secondKeys.Count + 1]; headerRow[0] = string.Empty; for (int j = 0; j < secondKeys.Count; j++) { headerRow[j + 1] = secondKeys[j].ToString(); } b.Append(StringUtils.ToCSVString(headerRow)).Append('\n'); foreach (K1 rowLabel in firstKeys) { string[] row = new string[secondKeys.Count + 1]; row[0] = rowLabel.ToString(); for (int j_1 = 0; j_1 < secondKeys.Count; j_1++) { K2 colLabel = secondKeys[j_1]; row[j_1 + 1] = nf.Format(GetCount(rowLabel, colLabel)); } b.Append(StringUtils.ToCSVString(row)).Append('\n'); } return(b.ToString()); }
public void PhoneNumberFromFormat(NumberFormat format, int length, string startsWith) { var randomNumbers = Gen.Random.PhoneNumbers.WithFormat(format); for (int i = 0; i < 100; i++) { var number = randomNumbers(); Console.WriteLine(number); Assert.Equal(length, number.Length); Assert.True(number.StartsWith(startsWith)); } }
internal NumberFormatInfo(Locale locale) { _locale = locale; _numbers = NumberFormat.GetNumberInstance(locale); _symbols = new DecimalFormatSymbols(locale) { Infinity = "Infinity" }; _decimals = _numbers as DecimalFormat ?? new DecimalFormat(); _decimals.DecimalFormatSymbols = _symbols; _currency = NumberFormat.GetCurrencyInstance(locale) as DecimalFormat ?? _decimals; _percent = NumberFormat.GetPercentInstance(locale) as DecimalFormat ?? _decimals; }
string NumberFormatToMask(NumberFormat format) { switch (format) { case NumberFormat.UKLandLine: return "01xxx xxxxxx"; case NumberFormat.UKMobile: return "07xxx xxxxxx"; default: throw new NotSupportedException(string.Format("Format {0} is not supported.", format)); } }
public override void readExternal(ObjectInput objectInput) { boolean hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setGeneralDesc(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setFixedLine(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setMobile(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setTollFree(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setPremiumRate(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setSharedCost(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setPersonalNumber(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setVoip(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setPager(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setUan(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setEmergency(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setVoicemail(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setShortCode(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setStandardRate(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setCarrierSpecific(desc); } hasDesc = objectInput.readBoolean(); if (hasDesc) { PhoneNumberDesc desc = new PhoneNumberDesc(); desc.readExternal(objectInput); setNoInternationalDialling(desc); } setId(objectInput.readUTF()); setCountryCode(objectInput.readInt()); setInternationalPrefix(objectInput.readUTF()); boolean hasString = objectInput.readBoolean(); if (hasString) { setPreferredInternationalPrefix(objectInput.readUTF()); } hasString = objectInput.readBoolean(); if (hasString) { setNationalPrefix(objectInput.readUTF()); } hasString = objectInput.readBoolean(); if (hasString) { setPreferredExtnPrefix(objectInput.readUTF()); } hasString = objectInput.readBoolean(); if (hasString) { setNationalPrefixForParsing(objectInput.readUTF()); } hasString = objectInput.readBoolean(); if (hasString) { setNationalPrefixTransformRule(objectInput.readUTF()); } setSameMobileAndFixedLinePattern(objectInput.readBoolean()); int nationalFormatSize = objectInput.readInt(); for (int i = 0; i < nationalFormatSize; i++) { NumberFormat numFormat = new NumberFormat(); numFormat.readExternal(objectInput); numberFormat_.add(numFormat); } int intlNumberFormatSize = objectInput.readInt(); for (int i = 0; i < intlNumberFormatSize; i++) { NumberFormat numFormat = new NumberFormat(); numFormat.readExternal(objectInput); intlNumberFormat_.add(numFormat); } setMainCountryForCode(objectInput.readBoolean()); hasString = objectInput.readBoolean(); if (hasString) { setLeadingDigits(objectInput.readUTF()); } setLeadingZeroPossible(objectInput.readBoolean()); }
public LanguageWriter(IFormatter formatter, ILanguageWriterConfiguration configuration) { this.formatter = formatter; this.configuration = configuration; if (specialTypeNames == null) { specialTypeNames = new Hashtable(); specialTypeNames["Void"] = " "; specialTypeNames["Object"] = "TObject"; specialTypeNames["String"] = "string"; specialTypeNames["SByte"] = "Shortint"; specialTypeNames["Byte"] = "Byte"; specialTypeNames["Int16"] = "Smallint"; specialTypeNames["UInt16"] = "Word"; specialTypeNames["Int32"] = "Integer"; specialTypeNames["UInt32"] = "Cardinal"; specialTypeNames["Int64"] = "Int64"; specialTypeNames["UInt64"] = "UInt64"; specialTypeNames["Char"] = "Char"; specialTypeNames["Boolean"] = "boolean"; specialTypeNames["Single"] = "Single"; specialTypeNames["Double"] = "Double"; specialTypeNames["Decimal"] = "Decimal"; } if (specialMethodNames == null) { specialMethodNames = new Hashtable(); specialMethodNames["op_UnaryPlus"] = "Positive"; specialMethodNames["op_Addition"] = "Add"; specialMethodNames["op_Increment"] = "Inc"; specialMethodNames["op_UnaryNegation"] = "Negative"; specialMethodNames["op_Subtraction"] = "Subtract"; specialMethodNames["op_Decrement"] = "Dec"; specialMethodNames["op_Multiply"] = "Multiply"; specialMethodNames["op_Division"] = "Divide"; specialMethodNames["op_Modulus"] = "Modulus"; specialMethodNames["op_BitwiseAnd"] = "BitwiseAnd"; specialMethodNames["op_BitwiseOr"] = "BitwiseOr"; specialMethodNames["op_ExclusiveOr"] = "BitwiseXor"; specialMethodNames["op_Negation"] = "LogicalNot"; specialMethodNames["op_OnesComplement"] = "BitwiseNot"; specialMethodNames["op_LeftShift"] = "ShiftLeft"; specialMethodNames["op_RightShift"] = "ShiftRight"; specialMethodNames["op_Equality"] = "Equal"; specialMethodNames["op_Inequality"] = "NotEqual"; specialMethodNames["op_GreaterThanOrEqual"] = "GreaterThanOrEqual"; specialMethodNames["op_LessThanOrEqual"] = "LessThanOrEqual"; specialMethodNames["op_GreaterThan"] = "GreaterThan"; specialMethodNames["op_LessThan"] = "LessThan"; specialMethodNames["op_True"] = "True"; specialMethodNames["op_False"] = "False"; specialMethodNames["op_Implicit"] = "Implicit"; specialMethodNames["op_Explicit"] = "Explicit"; } switch (configuration["NumberFormat"]) { case "Hexadecimal": this.numberFormat = NumberFormat.Hexadecimal; break; case "Decimal": this.numberFormat = NumberFormat.Decimal; break; default: this.numberFormat = NumberFormat.Auto; break; } }
public Func<string> WithFormat(NumberFormat format) { return FromMask(NumberFormatToMask(format)); }
/// <summary> /// Converts the number to the given format. This is nice because you don't have to remember or look up format strings. /// </summary> /// <param name="value">The value to format.</param> /// <param name="format">The type of format to use.</param> /// <param name="culture">The culture info used to format. If null, the Thread.CurrentThread.CurrentCulture will be used.</param> public static string ToString(this double value, NumberFormat format, CultureInfo culture) { return value.ToString(format, culture, null); }
public static void PrintFormattedNumber(object number, NumberFormat format) { switch (format) { case NumberFormat.Float: Console.WriteLine("{0:f2}", number); break; case NumberFormat.Percent: Console.WriteLine("{0:p0}", number); break; case NumberFormat.PaddedRight: Console.WriteLine("{0,8}", number); break; default: throw new ArgumentException("Invalid format!"); // should never happen } }
/** * Formats a double value to produce a string. In general, the value is * formatted using the formatting rules of <code>format</code>. There are * three exceptions to this: * <ol> * <li>NaN is formatted as '(NaN)'</li> * <li>Positive infinity is formatted as '(Infinity)'</li> * <li>Negative infinity is formatted as '(-Infinity)'</li> * </ol> * * @param value the double to format. * @param format the format used. * @param toAppendTo where the text is to be appended * @param pos On input: an alignment field, if desired. On output: the * offsets of the alignment field * @return the value passed in as toAppendTo. */ public static StringBuilder formatDouble(double value, NumberFormat format, StringBuilder toAppendTo, FieldPosition pos) { if( Double.isNaN(value) || Double.isInfinite(value) ) { toAppendTo.Append('('); toAppendTo.Append(value); toAppendTo.Append(')'); } else { format.format(value, toAppendTo, pos); } return toAppendTo; }
private static NumberFormat.Builder Update(NumberFormat p) { return new NumberFormat.Builder().MergeFrom(p); }
public static string ToString(int[][] counts, Object[] rowLabels, Object[] colLabels, int labelSize, int cellSize, NumberFormat nf, bool printTotals) { if (counts.Length == 0 || counts[0].Length == 0) return @""; int[] rowTotals = new int[counts.Length]; int[] colTotals = new int[counts[0].Length]; int total = 0; for (int i = 0; i < counts.Length; i++) { for (int j = 0; j < counts[i].Length; j++) { rowTotals[i] += counts[i][j]; colTotals[j] += counts[i][j]; total += counts[i][j]; } } StringBuilder result = new StringBuilder(); if (colLabels != null) { result.Append(StringUtils.PadLeft(@"", labelSize)); for (int j = 0; j < counts[0].Length; j++) { string s = (colLabels[j] == null ? @"null" : colLabels[j].ToString()); if (s.Length() > cellSize - 1) { s = s.Substring(0, cellSize - 1); } s = StringUtils.PadLeft(s, cellSize); result.Append(s); } if (printTotals) { result.Append(StringUtils.PadLeftOrTrim(@"Total", cellSize)); } result.Append('\n'); } for (int i = 0; i < counts.Length; i++) { if (rowLabels != null) { string s = (rowLabels[i] == null ? @"null" : rowLabels[i].ToString()); s = StringUtils.PadOrTrim(s, labelSize); result.Append(s); } for (int j = 0; j < counts[i].Length; j++) { result.Append(StringUtils.PadLeft(nf.Format(counts[i][j]), cellSize)); } if (printTotals) { result.Append(StringUtils.PadLeft(nf.Format(rowTotals[i]), cellSize)); } result.Append('\n'); } if (printTotals) { result.Append(StringUtils.Pad(@"Total", labelSize)); foreach (int colTotal in colTotals) { result.Append(StringUtils.PadLeft(nf.Format(colTotal), cellSize)); } result.Append(StringUtils.PadLeft(nf.Format(total), cellSize)); } return result.ToString(); }
private static void SerializeFormat(StringBuilder sb, int indentation, NumberFormat? numberFormat) { if (numberFormat == null) return; sb.AppendFormat("format: {0}{1}".Indent(indentation + 4), GetFormat(numberFormat)); sb.AppendLine(); }
public CompassView(Context context, Android.Util.IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { _paint = new Paint(); _paint.SetStyle(Paint.Style.Fill); _paint.AntiAlias = true; _paint.TextSize = (float)DIRECTION_TEXT_HEIGHT; _paint.SetTypeface(Typeface.Create("sans-serif-thin", TypefaceStyle.Normal)); _tickPaint = new Paint(); _tickPaint.SetStyle(Paint.Style.Stroke); _tickPaint.StrokeWidth = (float)TICK_WIDTH; _tickPaint.AntiAlias = true; _tickPaint.Color = Color.White; _placePaint = new TextPaint(); _placePaint.SetStyle(Paint.Style.Fill); _placePaint.AntiAlias = true; _placePaint.Color = Color.White; _placePaint.TextSize = (float)PLACE_TEXT_HEIGHT; _placePaint.SetTypeface(Typeface.Create("sans-serif-light", TypefaceStyle.Normal)); _path = new Path(); _textBounds = new Rect(); _allBounds = new List<Rect>(); _distanceFormat = NumberFormat.GetNumberInstance(Locale.Default); _distanceFormat.MinimumFractionDigits = 0; _distanceFormat.MaximumFractionDigits = 1; _placeBitmap = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.place_mark); _animatedHeading = Double.NaN; _directions = context.Resources.GetStringArray(Resource.Array.direction_abbreviations); _animator = new ValueAnimator(); setupAnimator(); }
public Number(NumberFormat format, uint val, uint len = 0) { this.Format = format; this.Value = val; this.LiteralLength = len; }
/// <summary> /// Converts the number to the given format. This is nice because you don't have to remember or look up format strings. Uses the current thread's culture. /// </summary> /// <param name="value">The value to format.</param> /// <param name="format">The type of format to use.</param> /// <param name="culture">The culture info used to format. If null, the Thread.CurrentThread.CurrentCulture will be used.</param> /// <param name="decimals">The number of decimals to force the formatted value to. If null, the amount of natural decimals will be used.</param> public static string ToString(this double value, NumberFormat format) { return value.ToString(format, null, null); }
/// <summary> /// Converts the number to the given format. This is nice because you don't have to remember or look up format strings. /// </summary> /// <param name="value">The value to format.</param> /// <param name="format">The type of format to use.</param> /// <param name="culture">The culture info used to format. If null, the Thread.CurrentThread.CurrentCulture will be used.</param> /// <param name="decimals">The number of decimals to force the formatted value to. If null, the amount of natural decimals will be used.</param> public static string ToString(this double value, NumberFormat format, CultureInfo culture, int? decimals) { if (decimals.HasValue && decimals.Value < 0) throw new ArgumentOutOfRangeException("decimals must be 0 or greater."); if (culture == null) culture = Threading.Thread.CurrentThread.CurrentCulture; string formatString; switch (format) { case NumberFormat.FixedPoint: formatString = "f" + decimals; break; case NumberFormat.General: formatString = "g"; break; case NumberFormat.Number: formatString = "n" + decimals; break; case NumberFormat.Currency: formatString = "c" + decimals; break; case NumberFormat.Percentage: formatString = "p" + decimals; break; case NumberFormat.Scientific: formatString = "e" + decimals; break; default: throw new InvalidEnumArgumentException(); } return value.ToString(formatString, culture.NumberFormat); }
public PhoneMetadata addNumberFormat(NumberFormat value) { if (value == null) { throw new NullPointerException(); } numberFormat_.add(value); return this; }
static EventLogger() { TimeFormat = NumberFormat.GetInstance(Locale.Us); TimeFormat.MinimumFractionDigits = 2; TimeFormat.MaximumFractionDigits = 2; }
public NumberFormat mergeFrom(NumberFormat other) { if (other.hasPattern()) { setPattern(other.getPattern()); } if (other.hasFormat()) { setFormat(other.getFormat()); } int leadingDigitsPatternSize = other.leadingDigitsPatternSize(); for (int i = 0; i < leadingDigitsPatternSize; i++) { addLeadingDigitsPattern(other.getLeadingDigitsPattern(i)); } if (other.hasNationalPrefixFormattingRule()) { setNationalPrefixFormattingRule(other.getNationalPrefixFormattingRule()); } if (other.hasDomesticCarrierCodeFormattingRule()) { setDomesticCarrierCodeFormattingRule(other.getDomesticCarrierCodeFormattingRule()); } setNationalPrefixOptionalWhenFormatting(other.isNationalPrefixOptionalWhenFormatting()); return this; }
public static string ToString(byte[] a, NumberFormat nf) { if (a == null) return null; if (a.Length == 0) return @"[]"; StringBuilder b = new StringBuilder(); b.Append('['); for (int i = 0; i < a.Length - 1; i++) { string s; if (nf == null) { s = String.ValueOf(a[i]); } else { s = nf.Format(a[i]); } b.Append(s); b.Append(@", "); } string s; if (nf == null) { s = String.ValueOf(a[a.Length - 1]); } else { s = nf.Format(a[a.Length - 1]); } b.Append(s); b.Append(']'); return b.ToString(); }
/** * Parses <code>source</code> for a number. This method can parse normal, * numeric values as well as special values. These special values include * Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY. * * @param source the string to parse * @param format the number format used to parse normal, numeric values. * @param pos input/ouput parsing parameter. * @return the parsed number. */ public static Number parseNumber(String source, NumberFormat format, ParsePosition pos) { int startIndex = pos.getIndex(); Number number = format.parse(source, pos); int endIndex = pos.getIndex(); // check for error parsing number if (startIndex == endIndex) { // try parsing special numbers double[] special = { Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY }; for (int i = 0; i < special.length; ++i) { number = parseNumber(source, special[i], pos); if (number != null) { break; } } } return number; }
public static string FormatNumber(double number, NumberFormat format) { switch (format) { case NumberFormat.Normal: return number.ToString(CultureInfo.InvariantCulture); case NumberFormat.Group: return String.Format("{0:n0}", number); case NumberFormat.GroupCommas: return number.ToString("n0", CommaGroupFormat); case NumberFormat.GroupDots: return number.ToString("n0", DotGroupFormat); case NumberFormat.Roman: case NumberFormat.RomanUpper: { if (number <= 0 || number > MaxRomanValue || number % 1 > 0) return "?"; var intArr = number.ToString(CultureInfo.InvariantCulture).Reverse().Select(c => Int32.Parse(c.ToString(CultureInfo.InvariantCulture))).ToArray(); var sb = new StringBuilder(); for (int i = intArr.Length; i-- > 0; ) { sb.Append(RomanNumerals[i][intArr[i]]); } return sb.ToString(); } case NumberFormat.RomanLower: { if (number <= 0 || number > MaxRomanValue || number % 1 > 0) return "?"; var intArr = number.ToString(CultureInfo.InvariantCulture).Reverse().Select(c => Int32.Parse(c.ToString(CultureInfo.InvariantCulture))).ToArray(); var sb = new StringBuilder(); for (int i = intArr.Length; i-- > 0; ) { sb.Append(RomanNumerals[i][intArr[i]]); } return sb.ToString().ToLower(); } case NumberFormat.VerbalEn: { return number % 1 > 0 ? "?" : ToVerbal((long)number); } } return number.ToString(CultureInfo.InvariantCulture); }
private static string GetFormat(NumberFormat? numberFormat) { return Enum.GetName(typeof(NumberFormat), numberFormat.Value).ToLowerInvariant(); }
/// <summary> /// Converts the number to the given format. This is nice because you don't have to remember or look up format strings. Uses the current thread's culture. /// </summary> /// <param name="value">The value to format.</param> /// <param name="format">The type of format to use.</param> /// <param name="decimals">The number of decimals to force the formatted value to. If null, the amount of natural decimals will be used.</param> public static string ToString(this double value, NumberFormat format, int? decimals) { return value.ToString(format, null, decimals); }