コード例 #1
0
        private void SetFormatersForNumberBoxes()
        {
            IncrementNumberRounder rounder = new IncrementNumberRounder();

            rounder.Increment         = 1;
            rounder.RoundingAlgorithm = RoundingAlgorithm.RoundHalfUp;
            DecimalFormatter formatter = new DecimalFormatter();

            formatter.IntegerDigits  = 1;
            formatter.FractionDigits = 0;
            formatter.NumberRounder  = rounder;
            nb1.NumberFormatter      = formatter;
            nb2.NumberFormatter      = formatter;
            nb3.NumberFormatter      = formatter;
            nb4.NumberFormatter      = formatter;
        }
コード例 #2
0
        // Uses DecimalFormatter to validate that input is compliant
        void ValidateInput(object sender, RoutedEventArgs e)
        {
            bool isEval = false;

            // Handles case for empty textbox, should remain valid and treated by value as 0 input for now
            if (this.Text == "" && !IsOutOfBounds(0))
            {
                Value = 0;
                SetErrorState(false);
                return;
            }


            if (BasicValidationMode == NumberBoxBasicValidationMode.Disabled)
            {
                return;
            }

            if (AcceptsCalculation)
            {
                EvaluateInput();
                isEval = true;
            }

            DecimalFormatter  df        = this.Formatter;
            Nullable <double> parsedNum = df.ParseDouble(this.Text);

            // Give Validaton error if no match
            if (parsedNum == null || IsOutOfBounds((double)parsedNum))
            {
                // Overwrite with last  value when invalid value is parsed
                if (BasicValidationMode == NumberBoxBasicValidationMode.InvalidInputOverwritten && !isEval)
                {
                    SetErrorState(false);
                    ProcessInput(Value);
                    return;
                }

                SetErrorState(true);
            }
            else
            {
                // Set Valid state and start input processing
                SetErrorState(false);
                ProcessInput((double)parsedNum);
            }
        }
コード例 #3
0
        private void SetNumberBoxNumberFormatter()
        {
            IncrementNumberRounder rounder = new IncrementNumberRounder
            {
                Increment         = 0.25,
                RoundingAlgorithm = RoundingAlgorithm.RoundHalfUp
            };

            DecimalFormatter formatter = new DecimalFormatter
            {
                IntegerDigits  = 1,
                FractionDigits = 2,
                NumberRounder  = rounder
            };

            FormattedNumberBox.NumberFormatter = formatter;
        }
コード例 #4
0
    private string GenerateValue_ValueString(string resourceString, double ratingValue)
    {
        DecimalFormatter formatter             = new DecimalFormatter();
        SignificantDigitsNumberRounder rounder = new SignificantDigitsNumberRounder();

        formatter.NumberRounder = rounder;

        string maxRatingString = GetRatingControl().MaxRating.ToString();

        int fractionDigits = DetermineFractionDigits(ratingValue);
        int sigDigits      = DetermineSignificantDigits(ratingValue, fractionDigits);

        formatter.FractionDigits  = fractionDigits;
        rounder.SignificantDigits = (uint)sigDigits;
        string ratingString = formatter.Format(ratingValue);

        return(StringUtil.FormatString(resourceString, ratingString, maxRatingString));
    }
コード例 #5
0
        void SetFontSizeResources()
        {
#if true // HAS_UNO
            FontTable currentItem = fontTables.First(f => f.numericSystem == "Default");
#else
            DecimalFormatter formatter = LocalizationService.GetRegionalSettingsAwareDecimalFormatter();

            FontTable currentItem = fontTables.First(f => f.numericSystem == formatter.NumeralSystem);
#endif

            this.Resources.Add(("ResultFullFontSize"), currentItem.fullFont);
            this.Resources.Add(("ResultFullMinFontSize"), currentItem.fullFontMin);
            this.Resources.Add(("ResultPortraitMinFontSize"), currentItem.portraitMin);
            this.Resources.Add(("ResultSnapFontSize"), currentItem.snapFont);
            this.Resources.Add(("CalcButtonCaptionSizeOverride"), currentItem.fullNumPadFont);
            this.Resources.Add(("CalcButtonScientificSnapCaptionSizeOverride"), currentItem.snapScientificNumPadFont);
            this.Resources.Add(("CalcButtonScientificPortraitCaptionSizeOverride"), currentItem.portraitScientificNumPadFont);
        }
コード例 #6
0
ファイル: NumberBox.cs プロジェクト: wiltonlazary/uno
        public NumberBox()
        {
            // Default values for the number formatter
            var formatter = new DecimalFormatter();

            formatter.IntegerDigits  = 1;
            formatter.FractionDigits = 0;
            NumberFormatter          = formatter;

            PointerWheelChanged += OnNumberBoxScroll;

            GotFocus  += OnNumberBoxGotFocus;
            LostFocus += OnNumberBoxLostFocus;

            Loaded   += (s, e) => InitializeTemplate();
            Unloaded += (s, e) => DisposeRegistrations();

            DefaultStyleKey = this;
        }
コード例 #7
0
        private void NumberBox_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            NumberBox numberBox = sender as NumberBox;

            // define rounding
            IncrementNumberRounder numberRounder = new IncrementNumberRounder
            {
                Increment = 1
            };

            // define formatting
            DecimalFormatter formatter = new DecimalFormatter
            {
                IntegerDigits  = 1,
                FractionDigits = 0,
                IsGrouped      = false,
                NumberRounder  = numberRounder
            };

            numberBox.NumberFormatter = formatter;
        }
コード例 #8
0
        public async void SetContext(LastArtist artist)
        {
            this.DataContext = LastART = artist;

            audictiveButton.Visibility = Ctr_Artist.Current.ArtistExists(new Artist()
            {
                Name = artist.Name
            }) ? Visibility.Visible : Visibility.Collapsed;

            buttonsArea.Visibility = Visibility.Collapsed;

            BitmapImage b = new BitmapImage();

            rootBrush.ImageSource = b;
            b.UriSource           = LastART.MainImage.Large;

            ellipse.SetSource(LastART.MainImage.Large, CircleImage.ImageType.LastFmArtist);

            title.Text = LastART.Name.ToUpper();
            //subtitle1.Text = Convert.ToString(LastART.PlayCount);
            var tags = LastART.Tags.ToList();

            lastFmTagsList.ItemsSource = tags;

            // FORMAT THE LISTENERS COUNT TO DISPLAY AS A GROUPED INT (1,000,000)
            DecimalFormatter formatter = new DecimalFormatter()
            {
                IsGrouped      = true,
                FractionDigits = 0
            };

            try
            {
                playCount.Text = formatter.FormatInt(LastART.Stats.Listeners) + " " + ApplicationInfo.Current.Resources.GetString("Listeners").ToUpper();
            }
            catch
            {
            }
        }
コード例 #9
0
        private void NumberBox_Loaded(object sender, RoutedEventArgs e)
        {
            NumberBox numberBox = sender as NumberBox;

            // define rounding
            IncrementNumberRounder numberRounder = new IncrementNumberRounder
            {
                Increment = 0.01
            };

            // define formatting
            DecimalFormatter formatter = new DecimalFormatter
            {
                IntegerDigits  = 1,
                FractionDigits = 2,
                IsGrouped      = false,
                IsDecimalPointAlwaysDisplayed = true,
                NumberRounder = numberRounder
            };

            numberBox.NumberFormatter = formatter;
        }
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime          = new DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar           = new Calendar();
                decimalFormatter   = new DecimalFormatter();
                geofenceCollection = new  ObservableCollection <GeofenceItem>();
                eventCollection    = new ObservableCollection <string>();

                // Geofencing setup
                InitializeGeolocation();

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                FillRegisteredGeofenceListBoxWithExistingGeofences();
                FillEventListBoxWithExistingEvents();

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;
            }
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past
                _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
コード例 #11
0
 public WinRTNumberFormatter(DecimalFormatter formatter)
 {
     _formatter = formatter;
 }
コード例 #12
0
        /// <summary>
        /// This is the click handler for the 'Display' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Display_Click(object sender, RoutedEventArgs e)
        {
            // This scenario uses language tags with unicode extensions to construct and use the various
            // formatters and NumeralSystemTranslator in Windows.Globalization.NumberFormatting to format numbers

            // Keep results of the scenario in a StringBuilder
            StringBuilder results = new StringBuilder();

            // Create number to format.
            double randomNumber = (new Random().NextDouble() * 100000);

            results.AppendLine("Random number used by formatters: " + randomNumber);
            // Create a string to translate
            String stringToTranslate = "These are the 10 digits of a numeral system: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9";

            results.AppendLine("String used by NumeralSystemTranslater: " + stringToTranslate);
            // Create the rounder and set its increment to 0.01
            IncrementNumberRounder rounder = new Windows.Globalization.NumberFormatting.IncrementNumberRounder();

            rounder.Increment = 0.001;
            results.AppendLine("CurrencyFormatter will be using Euro symbol and all formatters rounding to 0.001 increments");
            results.AppendLine();

            // The list of language tags with unicode extensions we want to test
            String[] languages = new[] { "de-DE-u-nu-telu-ca-buddist-co-phonebk-cu-usd", "ja-jp-u-nu-arab" };

            // Create the various formatters, now using the language list with unicode extensions
            results.AppendLine("Creating formatters using following languages in the language list:");
            foreach (String language in languages)
            {
                results.AppendLine("\t" + language);
            }
            results.AppendLine();

            // Create the various formatters.
            DecimalFormatter decimalFormatter = new DecimalFormatter(languages, "ZZ");

            decimalFormatter.NumberRounder = rounder; decimalFormatter.FractionDigits = 2;
            CurrencyFormatter currencyFormatter = new CurrencyFormatter(CurrencyIdentifiers.EUR, languages, "ZZ");

            currencyFormatter.NumberRounder = rounder; currencyFormatter.FractionDigits = 2;
            PercentFormatter percentFormatter = new PercentFormatter(languages, "ZZ");

            percentFormatter.NumberRounder = rounder; percentFormatter.FractionDigits = 2;
            PermilleFormatter permilleFormatter = new PermilleFormatter(languages, "ZZ");

            permilleFormatter.NumberRounder = rounder; permilleFormatter.FractionDigits = 2;
            NumeralSystemTranslator numeralTranslator = new NumeralSystemTranslator(languages);

            results.AppendLine("Using resolved language  " + decimalFormatter.ResolvedLanguage + "  : (note that all extension tags other than nu are ignored)");
            // Format using formatters and translate using NumeralSystemTranslator.
            results.AppendLine("Decimal Formatted:   " + decimalFormatter.Format(randomNumber));
            results.AppendLine("Currency formatted:   " + currencyFormatter.Format(randomNumber));
            results.AppendLine("Percent formatted:   " + percentFormatter.Format(randomNumber));
            results.AppendLine("Permille formatted:   " + permilleFormatter.Format(randomNumber));
            results.AppendLine("NumeralTranslator translated:   " + numeralTranslator.TranslateNumerals(stringToTranslate));
            results.AppendLine();

            // Display the results
            rootPage.NotifyUser(results.ToString(), NotifyType.StatusMessage);
        }
コード例 #13
0
        public static string NumberToString(string format, NumberFormatInfo nfi, Decimal value)
        {
            String hex;
            char   specifier;
            int    precision, digits, decimals;
            bool   underflow;

            //Console.WriteLine("!DecimalFormatter ToString format="+format);

            format = format.Trim();
            if (!DecimalFormatter.ParseFormat(format, out specifier, out precision))
            {
                throw new FormatException(Locale.GetText("The specified format is invalid"));
            }

            if (specifier == 'X')
            {
                digits    = (precision >= 0) ? precision : 0;
                underflow = DecimalEx.decimal2HexString(value, digits, format[0] == 'x', out hex);
                if (underflow)
                {
                    throw new FormatException(Locale.GetText("The specified format is invalid"));
                }

                return(hex);
            }

            digits   = -1;
            decimals = 0;
            // first calculate number of digits or decimals needed for format
            switch (specifier)
            {
            case 'C':
                decimals = (precision >= 0) ? precision : nfi.CurrencyDecimalDigits;
                break;

            case 'F': goto case 'N';

            case 'N':
                decimals = (precision >= 0) ? precision : nfi.NumberDecimalDigits;
                break;

            case 'G':
                digits = (precision >= 0) ? precision : 0;
                break;

            case 'E':
                digits = (precision >= 0) ? precision + 1 : 7;
                break;

            case 'P':
                decimals = (precision >= 0) ? precision + 2 : nfi.PercentDecimalDigits + 2;
                break;

            case 'Z':
                digits = 0;
                break;
            }

            // get digit string
            const int bufSize = 40;
            int       decPos = 0, sign = 0;

            char[] buf = new char[bufSize];
//			Console.WriteLine("  !calling decimal2string with lo {1}, mid {2}, hi {3} ,ss={0}",value.ss32,value.lo32,value.mid32,value.hi32);
            DecimalEx.decimal2string(value, digits, decimals, buf, bufSize, out decPos, out sign);
            string TempString = new String(buf);

            TempString = TempString.Trim(new char[] { (char)0x0 });

            //Console.WriteLine("  decimal2string returned '{0}'", TempString);
            StringBuilder sb = new StringBuilder(TempString, TempString.Length);

            if (sb.ToString() == String.Empty && decPos > 0 && sign == 0)
            {
                sb.Append('0');
            }

//			Console.WriteLine("  str '{0}', digits {1}, decPos {2}, sign {3} specifier={4}", TempString, digits, decPos, sign,specifier);

            // now build the format
            switch (specifier)
            {
            case 'C': return(FormatCurrency(nfi, sb, decimals, decPos, sign));

            case 'N': return(FormatNumber(nfi, sb, decimals, decPos, sign));

            case 'F': return(FormatFixedPoint(nfi, sb, decimals, decPos, sign));

            case 'G': return(FormatGeneral(nfi, sb, digits, decPos, sign, format[0]));

            case 'E': return(FormatExponential(nfi, sb, digits, decPos, sign, format[0], true));

            case 'P': return(FormatPercent(nfi, sb, decimals, decPos, sign));

            case 'Z': return(FormatNormalized(nfi, sb, digits, decPos, sign));

            default:
                throw new FormatException(Locale.GetText("The specified format is invalid"));
            }
        }
コード例 #14
0
            public override object Invoke(XsltContext xsltContext, object[] args, XPathNavigator docContext)
            {
                DecimalFormat formatInfo = ((XsltCompileContext)xsltContext).ResolveFormatName(args.Length == 3 ? ToString(args[2]) : null);

                return(DecimalFormatter.Format(ToNumber(args[0]), ToString(args[1]), formatInfo));
            }
コード例 #15
0
 public void FormatTest()
 {
     var polishCulture   = new CultureInfo("pl-PL");
     var polishFormatter = new DecimalFormatter(polishCulture);
        /// <summary>
        /// This is the click handler for the 'Display' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Display_Click(object sender, RoutedEventArgs e)
        {
            // This scenario uses the Windows.Globalization.NumberFormatting.DecimalFormatter,
            // Windows.Globalization.NumberFormatting.CurrencyFormatter and
            // Windows.Globalization.NumberFormatting.PercentFormatter classes to format and parse a number
            // percentage or currency.

            // Keep results of the scenario in a StringBuilder
            StringBuilder results = new StringBuilder();

            // Define percent formatters.
            PercentFormatter percentFormat   = new PercentFormatter();
            PercentFormatter percentFormatJP = new PercentFormatter(new string[] { "ja" }, "ZZ");
            PercentFormatter percentFormatFR = new PercentFormatter(new string[] { "fr-FR" }, "ZZ");

            // Define decimal formatters.
            DecimalFormatter decimalFormat = new DecimalFormatter();

            decimalFormat.IsGrouped = true;
            DecimalFormatter decimalFormatJP = new DecimalFormatter(new string[] { "ja" }, "ZZ");

            decimalFormatJP.IsGrouped = true;
            DecimalFormatter decimalFormatFR = new DecimalFormatter(new string[] { "fr-FR" }, "ZZ");

            decimalFormatFR.IsGrouped = true;

            // Define currency formatters
            string            userCurrency     = GlobalizationPreferences.Currencies[0];
            CurrencyFormatter currencyFormat   = new CurrencyFormatter(userCurrency);
            CurrencyFormatter currencyFormatJP = new CurrencyFormatter("JPY", new string[] { "ja" }, "ZZ");
            CurrencyFormatter currencyFormatFR = new CurrencyFormatter("EUR", new string[] { "fr-FR" }, "ZZ");

            // Generate numbers for parsing.
            double percentNumber  = 0.523;
            double decimalNumber  = 12345.67;
            double currencyNumber = 1234.56;

            // Roundtrip the percent numbers by formatting and parsing.
            String percent1       = percentFormat.Format(percentNumber);
            double percent1Parsed = percentFormat.ParseDouble(percent1).Value;

            String percent1JP       = percentFormatJP.Format(percentNumber);
            double percent1JPParsed = percentFormatJP.ParseDouble(percent1JP).Value;

            String percent1FR       = percentFormatFR.Format(percentNumber);
            double percent1FRParsed = percentFormatFR.ParseDouble(percent1FR).Value;

            // Generate the results for percent parsing.
            results.AppendLine("Percent parsing of " + percentNumber);
            results.AppendLine("Formatted for current user: "******" Parsed as current user: "******"Formatted for ja-JP: " + percent1JP + " Parsed for ja-JP: " + percent1JPParsed);
            results.AppendLine("Formatted for fr-FR: " + percent1FR + " Parsed for fr-FR: " + percent1FRParsed);
            results.AppendLine();

            // Roundtrip the decimal numbers for formatting and parsing.
            String decimal1       = decimalFormat.Format(decimalNumber);
            double decimal1Parsed = decimalFormat.ParseDouble(decimal1).Value;

            String decimal1JP       = decimalFormatJP.Format(decimalNumber);
            double decimal1JPParsed = decimalFormatJP.ParseDouble(decimal1JP).Value;

            String decimal1FR       = decimalFormatFR.Format(decimalNumber);
            double decimal1FRParsed = decimalFormatFR.ParseDouble(decimal1FR).Value;

            // Generate the results for decimal parsing.
            results.AppendLine("Decimal parsing of " + decimalNumber);
            results.AppendLine("Formatted for current user: "******" Parsed as current user: "******"Formatted for ja-JP: " + decimal1JP + " Parsed for ja-JP: " + decimal1JPParsed);
            results.AppendLine("Formatted for fr-FR: " + decimal1FR + " Parsed for fr-FR: " + decimal1FRParsed);
            results.AppendLine();

            // Roundtrip the currency numbers for formatting and parsing.
            String currency1       = currencyFormat.Format(currencyNumber);
            double currency1Parsed = currencyFormat.ParseDouble(currency1).Value;

            String currency1JP       = currencyFormatJP.Format(currencyNumber);
            double currency1JPParsed = currencyFormatJP.ParseDouble(currency1JP).Value;

            String currency1FR       = currencyFormatFR.Format(currencyNumber);
            double currency1FRParsed = currencyFormatFR.ParseDouble(currency1FR).Value;

            // Generate the results for decimal parsing.
            results.AppendLine("Currency parsing of " + currencyNumber);
            results.AppendLine("Formatted for current user: "******" Parsed as current user: "******"Formatted for ja-JP: " + currency1JP + " Parsed for ja-JP: " + currency1JPParsed);
            results.AppendLine("Formatted for fr-FR: " + currency1FR + " Parsed for fr-FR: " + currency1FRParsed);
            results.AppendLine();

            // Display the results.
            OutputTextBlock.Text = results.ToString();
        }
コード例 #17
0
 private void FuelUnitPrice(StringWriter receipt, double price)
 {
     receipt.WriteLine(DecimalFormatter.FormatStr(price, fuelUnitPriceDecimalPlace));
 }