/// <summary>
        /// Rounds the value specific to the wanted <see cref="RoundingType"/>.
        /// </summary>
        /// <param name="value">The value to round.</param>
        /// <param name="result">The rounded result value.</param>
        /// <param name="howToRound">How to round the value?</param>
        /// <param name="checkedCalculation">If true all possible exceptions are enabled.</param>
        /// <returns>The rounded value.</returns>
        /// <exception cref="ArgumentOutOfRangeException">The value to round is <see cref="double.NaN"/>!</exception>
        /// <exception cref="ArgumentOutOfRangeException">The value is not in the range of a <see cref="int"/>!</exception>
        /// <exception cref="ArgumentOutOfRangeException">The given <see cref="RoundingType"/> is not a valid <see cref="RoundingType"/>!</exception>
        public static void RoundSpecific(double value, out int result, RoundingType howToRound = RoundingType.Truncate, bool checkedCalculation = false)
        {
            if (checkedCalculation)
            {
                if (double.IsNaN(value))
                {
                    throw new ArgumentOutOfRangeException("The value to round is Not a Number!");
                }
                if (value < int.MinValue || value > int.MaxValue)
                {
                    throw new ArgumentOutOfRangeException("The value is not in the range of a byte!");
                }
            }
            double tempResult = FloatExtensions.RoundSpecific(value, howToRound);

            if (double.IsNaN(tempResult) || tempResult > int.MaxValue)
            {
                result = int.MaxValue;
            }
            else if (tempResult < int.MinValue)
            {
                result = int.MinValue;
            }
            else
            {
                result = (int)tempResult;
            }
        }
Exemplo n.º 2
0
        public static System.Drawing.Size ToDrawing(this System.Windows.Size size, RoundingType rounding = RoundingType.Round)
        {
            var width  = Round(size.Width, rounding);
            var height = Round(size.Height, rounding);

            return(new System.Drawing.Size(width, height));
        }
Exemplo n.º 3
0
        public static int Round(double num, RoundingType rounding = RoundingType.Round)
        {
            const double rounder = 0.4999999999; // Difficult to be precise without posible error.
            int          result;

            switch (rounding)
            {
            case RoundingType.Ceiling:
                result = (int)Math.Ceiling(num);
                break;

            case RoundingType.Up:
                result = (int)Math.Round(num + (Math.Sign(num) > 0 ? rounder : -rounder));
                break;

            case RoundingType.Round:
                result = (int)Math.Round(num);
                break;

            case RoundingType.Down:
                result = (int)Math.Round(num + (Math.Sign(num) < 0 ? rounder : -rounder));
                break;

            case RoundingType.Floor:
                result = (int)Math.Floor(num);
                break;

            default:
                throw new ArgumentException();
            }

            return(result);
        }
Exemplo n.º 4
0
 public PBNumber(NumberCapacity inWidth, String inSign, String inExponent, String inMantissa, RoundingType inRounding)
 {
     this.width = inWidth;
     switch (this.width)
     {
         case NumberCapacity.PB32:
             {
                 this.offset = NumberOffset.PB32;
                 this.exponentLenght = NumberExponentLength.PB32;
                 this.mantissaLenght = NumberMantissaLength.PB32;
                 this.mf = IPBNumber.NumberMFs[(int)NumberMF.PB32];
                 this.cf = IPBNumber.NumberCFs[(int)NumberCF.PB32];
                 break;
             }
         case NumberCapacity.PB64:
             {
                 this.offset = NumberOffset.PB64;
                 this.exponentLenght = NumberExponentLength.PB64;
                 this.mantissaLenght = NumberMantissaLength.PB64;
                 this.mf = IPBNumber.NumberMFs[(int)NumberMF.PB64];
                 this.cf = IPBNumber.NumberCFs[(int)NumberCF.PB64];
                 break;
             }
         case NumberCapacity.PB128:
             {
                 this.offset = NumberOffset.PB128;
                 this.exponentLenght = NumberExponentLength.PB128;
                 this.mantissaLenght = NumberMantissaLength.PB128;
                 this.mf = IPBNumber.NumberMFs[(int)NumberMF.PB128];
                 this.cf = IPBNumber.NumberCFs[(int)NumberCF.PB128];
                 break;
             }
         case NumberCapacity.PB256:
             {
                 this.offset = NumberOffset.PB256;
                 this.exponentLenght = NumberExponentLength.PB256;
                 this.mantissaLenght = NumberMantissaLength.PB256;
                 this.mf = IPBNumber.NumberMFs[(int)NumberMF.PB256];
                 this.cf = IPBNumber.NumberCFs[(int)NumberCF.PB256];
                 break;
             }
         default:
             {
                 break;
             }
     }
     this.name = "Name-" + this.width.ToString() + "[" + inSign + inExponent + "|" + inMantissa + "]";
     this.sign = inSign;
     this.Exponent = inExponent;
     this.Mantissa = inMantissa;
     this.roundingType = inRounding;
     if (pbConvertion == null)
         pbConvertion = new PBConvertion();
 }
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ (Expression != null ? Expression.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (RoundingType != null ? RoundingType.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (RoundingDecimalPlaces != null ? RoundingDecimalPlaces.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (DecimalPlacesToShow != null ? DecimalPlacesToShow.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Result != null ? Result.GetHashCode() : 0);
         return(hashCode);
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// 舍入
        /// </summary>
        /// <param name="d"></param>
        /// <param name="decimals">保留小数位数</param>
        /// <param name="Rounding">舍入方式</param>
        /// <returns></returns>
        internal static double Round(this double d, int decimals = 0, RoundingType Rounding = RoundingType.Normal)
        {
            switch (Rounding)
            {
            case RoundingType.Normal:
                return(Math.Round(d, decimals, MidpointRounding.AwayFromZero));

            case RoundingType.Banker:
                return(Math.Round(d, decimals, MidpointRounding.ToEven));

            default:
                throw new Exception("舍入法未知");
            }
        }
 public MASM_FormattingItem(ItemMode mode)
 {
     this.enable         = true;
     this.mode           = mode;
     this.property       = "";
     this.prefix         = "";
     this.postfix        = "";
     this.targetData     = TargetData.PropertyValue;
     this.operationType  = OperationType.None;
     this.operationValue = 0;
     this.roundMode      = RoundingType.None;
     this.modulo         = false;
     this.outFormat      = "";
 }
Exemplo n.º 8
0
    public static Expression RoundExpression(Expression value, decimal multiplier, RoundingType rounding)
    {
        var result = value;

        result = result.Type.UnNullify() == typeof(decimal) ?
                 result.UnNullify() :
                 Expression.Convert(result, typeof(double));

        if (rounding == RoundingType.RoundMiddle)
        {
            result = Expression.Subtract(result, Constant(multiplier / 2, result.Type));
        }

        if (multiplier != 1)
        {
            result = Expression.Divide(result, Constant(multiplier, result.Type));
        }

        if (rounding == RoundingType.Ceil)
        {
            result = result.Type.UnNullify() == typeof(decimal) ?
                     Expression.Call(miCeilingDecimal, result.UnNullify()) :
                     Expression.Call(miCeilingDouble, result.TryConvert(typeof(double)));
        }
        else if (rounding == RoundingType.Floor)
        {
            result = result.Type.UnNullify() == typeof(decimal) ?
                     Expression.Call(miFloorDecimal, result.UnNullify()) :
                     Expression.Call(miFloorDouble, result.TryConvert(typeof(double)));
        }
        else if (rounding == RoundingType.Round || rounding == RoundingType.RoundMiddle)
        {
            result = result.Type.UnNullify() == typeof(decimal) ?
                     Expression.Call(miRoundDecimal, result.UnNullify()) :
                     Expression.Call(miRoundDouble, result.TryConvert(typeof(double)));
        }

        if (multiplier != 1)
        {
            result = Expression.Multiply(result, Constant(multiplier, result.Type));
        }

        if (rounding == RoundingType.RoundMiddle)
        {
            result = Expression.Add(result, Constant(multiplier / 2, result.Type));
        }

        return(result.Nullify().TryConvert(value.Type.Nullify()));
    }
Exemplo n.º 9
0
        public static string GetDecimalDisplayFormat(RoundingType roundingType)
        {
            var decimalFormat = "0";

            if (roundingType == RoundingType.SiteDefaultDecimalPlace)
            {
                var decimalPlace = int.Parse(SiteDecimal_Place);
                if (decimalPlace > 0)
                {
                    decimalFormat += "." + new string('0', decimalPlace);
                }
            }
            else if (roundingType == RoundingType.SingleDecimalPlace)
            {
                decimalFormat += ".0";
            }
            return(decimalFormat);
        }
Exemplo n.º 10
0
        public static DiceDist NumDivWithRounding(DiceDist d, int q, RoundingType rounding)
        {
            var dD = new Dictionary <int, int>();

            foreach (var kvp in d._distributionDividends)
            {
                var newKey = Round((double)kvp.Key / q, rounding);
                if (dD.ContainsKey(newKey))
                {
                    dD[newKey] += kvp.Value;
                }
                else
                {
                    dD.Add(newKey, kvp.Value);
                }
            }

            return(new DiceDist(dD, d._divisor));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Làm tròn số
        /// </summary>
        /// <param name="value">Số cần làm tròn</param>
        /// <param name="digits">Số chữ số thập phân sau khi làm tròn</param>
        /// <param name="rounding">Làm tròn lên hay xuống</param>
        /// <returns>Trả lại số đã làm tròn</returns>
        public static decimal Rounding(this decimal value, int digits, RoundingType rounding = RoundingType.None)
        {
            double result = (double)value;
            int    number = digits;

            // Làm tròn trước số thập phân => chia để làm tròn như sau số thập phân
            if (digits < 0)
            {
                result = result / Math.Pow(10, -digits);
                number = 0;
            }

            // Làm tròn sau số thập phân
            // Chỉ xử lý nếu không phải làm tròn (cần thiết để Rounding.Up không bị làm tròn lên khi không cần làm tròn)
            if (result != result.ToString("0.".PadRight(2 + number, '#')).StringToDouble())
            {
                // Số lẻ cộng thêm để làm tròn lên hoặc trừ đi để làm tròn xuống
                double updown = 0.5 / Math.Pow(10, number);
                // Đảo dấu nếu là số âm
                if (result < 0)
                {
                    updown = 0 - updown;
                }

                switch (rounding)
                {
                case RoundingType.Up: result += updown; break;

                case RoundingType.Down: result -= updown; break;
                }
            }
            // Làm tròn
            result = Math.Round(result, number, MidpointRounding.AwayFromZero);

            // Khôi phục giá trị trước số thập phân
            if (digits < 0)
            {
                result = result * Math.Pow(10, -digits);
            }

            return((decimal)result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Round a value to have the provided total number of digits. For example, value 253.12332 with 5 digits would be 253.12
        /// </summary>
        /// <param name="value">The value to round</param>
        /// <param name="digits">The total amount of digits (NOT decimal places) to round to</param>
        /// <param name="roundingType">How to round</param>
        /// <returns></returns>
        public static decimal RoundToSignificantDigits(decimal value, int digits, RoundingType roundingType)
        {
            var val = (double)value;

            if (value == 0)
            {
                return(0);
            }

            double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(val))) + 1);

            if (roundingType == RoundingType.Closest)
            {
                return((decimal)(scale * Math.Round(val / scale, digits)));
            }
            else
            {
                return((decimal)(scale * (double)RoundDown((decimal)(val / scale), digits)));
            }
        }
Exemplo n.º 13
0
        private static int Round(double d, RoundingType rType)
        {
            switch (rType)
            {
            case RoundingType.ToEven:
                return((int)Math.Round(d, MidpointRounding.ToEven));

            case RoundingType.AwayFromZero:
                return((int)Math.Round(d, MidpointRounding.AwayFromZero));

            case RoundingType.Ceil:
                return((int)Math.Ceiling(d));

            case RoundingType.Floor:
                return((int)Math.Floor(d));

            default:
                throw new Exception("RoundingType not valid");
            }
        }
Exemplo n.º 14
0
        public static decimal GetRoundedValue(RoundingType roundingType, decimal value)
        {
            if (roundingType == RoundingType.SiteDefaultDecimalPlace)
            {
                value = Math.Round(value, int.Parse(SiteDecimal_Place));
            }
            else if (roundingType == RoundingType.DoubleDecimalplace)
            {
                value = Math.Round(value, 2);
            }
            else if (roundingType == RoundingType.SingleDecimalPlace)
            {
                value = Math.Round(value, 1);
            }
            else if (roundingType == RoundingType.NoDecimalPlace)
            {
                value = Math.Round(value, 0);
            }

            return(value);
        }
Exemplo n.º 15
0
        /// <summary>端数処理</summary>
        /// <param name="type">端数処理種別</param>
        /// <param name="value">値</param>
        /// <param name="precision">桁</param>
        /// <returns>計算結果。処理種別が取込不可の場合、切り捨て(エラー処理は外部で行うこと)</returns>
        public static decimal?Calc(this RoundingType type, decimal value, int precision)
        {
            decimal powered = value * Pow10(precision);
            decimal result  = 0;

            switch (type)
            {
            case RoundingType.Floor:
            case RoundingType.Error:
                result = Math.Abs(Math.Floor(powered)) * Math.Sign(powered);
                break;

            case RoundingType.Ceil:
                result = Math.Abs(Math.Ceiling(powered)) * Math.Sign(powered);
                break;

            case RoundingType.Round:
                result = Math.Round(powered, MidpointRounding.AwayFromZero);
                break;
            }
            return(result * Pow10(-precision));
        }
Exemplo n.º 16
0
        public PBNumber(String inDigit, NumberCapacity inCapacity, RoundingType inRounding)
            : this(inCapacity)
        {
            String currentNumber = "";
            this.InitValue = inDigit;

            IPBNumber.IFPartsOfNumber currentPartialNumber;
            IPBNumber.IFPartsOfNumber currentPartialNumber2cc;
            if (pbConvertion == null)
                pbConvertion = new PBConvertion();
            currentNumber = pbConvertion.NormalizeNumber(inDigit, PBConvertion.ACCURANCY, IPBNumber.NumberFormat.INTEGER);
            currentPartialNumber = pbConvertion.DenormalizeNumber(currentNumber, IPBNumber.NumberFormat.INTEGER);

            currentPartialNumber2cc.Sign = currentPartialNumber.Sign;
            currentPartialNumber2cc.IntegerPart = pbConvertion.convert10to2IPart(currentPartialNumber.IntegerPart);
            currentPartialNumber2cc.FloatPart = pbConvertion.convert10to2FPart(currentPartialNumber.FloatPart);

            //Define Exponent before Mantissa for correct running algorithm
            selectExp(currentPartialNumber2cc, inCapacity, IPBNumber.NumberFormat.INTEGER);
            selectMantissa(currentPartialNumber2cc, inCapacity, IPBNumber.NumberFormat.INTEGER, inRounding);
            this.Sign = currentPartialNumber.Sign;
        }
Exemplo n.º 17
0
        public static DiceDist DiceDiv(DiceDist a, DiceDist b, RoundingType rounding)
        {
            var dD = new Dictionary <int, int>();

            foreach (var kvpa in a._distributionDividends)
            {
                foreach (var kvpb in b._distributionDividends)
                {
                    var newKey = Round((double)kvpa.Key / kvpb.Key, rounding);
                    if (dD.ContainsKey(newKey))
                    {
                        // a and b are assumed independent, note divisors also multiplied
                        dD[newKey] += kvpa.Value * kvpb.Value;
                    }
                    else
                    {
                        dD.Add(newKey, kvpa.Value * kvpb.Value);
                    }
                }
            }

            return(new DiceDist(dD, a._divisor * b._divisor));
        }
Exemplo n.º 18
0
        protected override MutableObject Mutate(MutableObject mutable)
        {
            foreach (var entry in Operand.GetEntries(mutable))
            {
                var roundType = RoundingType.GetValue(entry);

                var operand = Operand.GetValue(entry);

                var denominator = Denominator.GetValue(entry);

                var outputValue = operand / denominator;

                if (roundType == RoundTypeEnum.Nearest)
                {
                    outputValue = Mathf.Round(outputValue);
                }
                else if (roundType == RoundTypeEnum.Down)
                {
                    outputValue = Mathf.Floor(outputValue);
                }
                else if (roundType == RoundTypeEnum.Up)
                {
                    outputValue = Mathf.Ceil(outputValue);
                }
                else if (roundType == RoundTypeEnum.Truncate)
                {
                    outputValue = (float)Math.Truncate(outputValue);
                }

                outputValue *= denominator;

                NearestTarget.SetValue(outputValue, entry);
            }

            return(mutable);
        }
        /// <summary>
        /// Rounds the value specific to the wanted <see cref="RoundingType"/>.
        /// </summary>
        /// <param name="value">The value to round.</param>
        /// <param name="result">The rounded result value.</param>
        /// <param name="howToRound">How to round the value?</param>
        /// <param name="checkedCalculation">If true all possible exceptions are enabled.</param>
        /// <returns>The rounded value.</returns>
        /// <exception cref="ArgumentOutOfRangeException">The value is not in the range of a <see cref="byte"/>!</exception>
        /// <exception cref="ArgumentOutOfRangeException">The given <see cref="RoundingType"/> is not a valid <see cref="RoundingType"/>!</exception>
        public static void RoundSpecific(decimal value, out byte result, RoundingType howToRound = RoundingType.Truncate, bool checkedCalculation = false)
        {
            if (checkedCalculation)
            {
                if (value < byte.MinValue || value > byte.MaxValue)
                {
                    throw new ArgumentOutOfRangeException("The value is not in the range of a byte!");
                }
            }
            decimal tempResult = FloatExtensions.RoundSpecific(value, howToRound);

            if (tempResult > byte.MaxValue)
            {
                result = byte.MaxValue;
            }
            else if (tempResult < byte.MinValue)
            {
                result = byte.MinValue;
            }
            else
            {
                result = (byte)tempResult;
            }
        }
Exemplo n.º 20
0
 public void CanRound(decimal valueToRounding, decimal roundedValue, RoundingType roundingType)
 {
     _priceCalcService.Round(valueToRounding, roundingType).Should().Be(roundedValue);
 }
 public void can_round(decimal valueToRoundig, decimal roundedValue, RoundingType roundingType)
 {
     _priceCalcService.Round(valueToRoundig, roundingType).ShouldEqual(roundedValue);
 }
Exemplo n.º 22
0
 public void can_round(decimal valueToRoundig, decimal roundedValue, RoundingType roundingType)
 {
     valueToRoundig.Round(roundingType).ShouldEqual(roundedValue);
 }
Exemplo n.º 23
0
 public static string GetDecimalDisplayFormat(RoundingType roundingType)
 {
     var decimalFormat = "0";
     if (roundingType == RoundingType.SiteDefaultDecimalPlace)
     {
         var decimalPlace = int.Parse(SiteDecimal_Place);
         if (decimalPlace > 0)
         {
             decimalFormat += "." + new string('0', decimalPlace);
         }
     }
     else if (roundingType == RoundingType.SingleDecimalPlace)
         decimalFormat += ".0";
     return decimalFormat;
 }
Exemplo n.º 24
0
 public StepRoundingToken(StepMultiplierToken parent, RoundingType rounding)
     : base(parent)
 {
     this.Rounding = rounding;
 }
Exemplo n.º 25
0
 public StepRoundingToken(StepMultiplierToken parent, RoundingType rounding)
 {
     this.parent   = parent ?? throw new ArgumentNullException(nameof(parent));
     this.Rounding = rounding;
 }
Exemplo n.º 26
0
        public static decimal GetRoundedValue(RoundingType roundingType, decimal value)
        {
            if (roundingType == RoundingType.SiteDefaultDecimalPlace)
                value = Math.Round(value, int.Parse(SiteDecimal_Place));
            else if (roundingType == RoundingType.DoubleDecimalplace)
                value = Math.Round(value, 2);
            else if (roundingType == RoundingType.SingleDecimalPlace)
                value = Math.Round(value, 1);
            else if (roundingType == RoundingType.NoDecimalPlace)
                value = Math.Round(value, 0);

            return value;
        }
        public void AdjustValuePrecisionTests(decimal min, decimal max, int?precision, RoundingType roundingType, decimal input, decimal expected)
        {
            var result = ExchangeHelpers.AdjustValuePrecision(min, max, precision, roundingType, input);

            Assert.AreEqual(expected, result);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Adjust a value to be between the min and max parameters and rounded to the closest step.
        /// </summary>
        /// <param name="min">The min value</param>
        /// <param name="max">The max value</param>
        /// <param name="step">The step size the value should be floored to. For example, value 2.548 with a step size of 0.01 will output 2.54</param>
        /// <param name="roundingType">How to round</param>
        /// <param name="value">The input value</param>
        /// <returns></returns>
        public static decimal AdjustValueStep(decimal min, decimal max, decimal?step, RoundingType roundingType, decimal value)
        {
            if (step == 0)
            {
                throw new ArgumentException($"0 not allowed for parameter {nameof(step)}, pass in null to ignore the step size", nameof(step));
            }

            value = Math.Min(max, value);
            value = Math.Max(min, value);
            if (step == null)
            {
                return(value);
            }

            var offset = value % step.Value;

            if (roundingType == RoundingType.Down)
            {
                value -= offset;
            }
            else
            {
                if (offset < step / 2)
                {
                    value -= offset;
                }
                else
                {
                    value += (step.Value - offset);
                }
            }

            value = RoundDown(value, 8);

            return(value.Normalize());
        }
Exemplo n.º 29
0
        public FormattedString Format(EcmaValue value)
        {
            EnsureInitialized();
            NumberFormatInfo formatter = formatProvider.FormatProvider;

            value = value.ToNumber();
            if (value.IsNaN || !value.IsFinite)
            {
                string str = value.ToDouble().ToString(formatter);
                return(new FormattedString(new[] { new FormattedPart(value.IsNaN ? FormattedPartType.NaN : FormattedPartType.Infinity, str) }));
            }

            double doubleValue = value.ToDouble();

            if (this.SignDisplay == SignDisplayFormat.Never)
            {
                doubleValue = Math.Abs(doubleValue);
            }
            if (this.Style == NumberStyle.Percent)
            {
                doubleValue *= 100;
            }
            PluralCategories    pluralCount     = pluralRules.Match(doubleValue);
            NumberFormatPattern notationFormats = this.Notation == NumberNotation.Compact ? GetCompactNotationPattern(doubleValue, pluralCount, out doubleValue) : this.notationFormats;
            NumberFormatPattern styleFormats    = this.styleFormats.Count == 1 ? this.styleFormats[PluralCategories.Other] : this.styleFormats[pluralCount];
            FormattedString     notationFormat  = null;
            FormattedString     styleFormat     = null;

            switch (doubleValue.CompareTo(0))
            {
            case -1:
                notationFormat = notationFormats.NegativePattern;
                styleFormat    = styleFormats.NegativePattern;
                break;

            case 0:
                notationFormat = notationFormats.ZeroPattern;
                styleFormat    = styleFormats.ZeroPattern;
                break;

            case 1:
                notationFormat = notationFormats.PositivePattern;
                styleFormat    = styleFormats.PositivePattern;
                break;
            }
            if (this.Digits.RoundingType == RoundingType.SignificantDigits)
            {
                doubleValue = RoundToSignificantDigits(doubleValue, this.Digits.MaximumSignificantDigits);
            }

            // format double value with corresponding notation (scienific, compact, ...)
            List <FormattedPart> numParts = new List <FormattedPart>(notationFormat);
            List <FormattedPart> subParts = new List <FormattedPart>();
            int    index     = numParts.FindIndex(v => v.Type == FormattedPartType.Placeholder);
            string formatted = doubleValue.ToString(numParts[index].Value, formatter);

            FormattedPartType integerType  = FormattedPartType.Integer;
            RoundingType      roundingType = this.Digits.RoundingType;
            int maxDigits   = roundingType == RoundingType.SignificantDigits ? this.Digits.MaximumSignificantDigits : -1;
            int numOfDigits = 0;

            foreach (Match m in Regex.Matches(formatted, "([0-9]+)|."))
            {
                FormattedPartType type = FormattedPartType.Literal;
                string            str  = m.Value;
                if (m.Groups[1].Success)
                {
                    type = integerType;
                    if (roundingType == RoundingType.SignificantDigits)
                    {
                        if (type != FormattedPartType.ExponentInteger)
                        {
                            numOfDigits += numOfDigits == 0 ? str.TrimStart('0').Length : str.Length;
                        }
                        if (type == FormattedPartType.Fraction && numOfDigits > maxDigits)
                        {
                            str = str.Substring(0, str.Length - numOfDigits + maxDigits);
                        }
                    }
                }
                else if (symbolType.TryGetValue(str, out type))
                {
                    if (type == FormattedPartType.Decimal)
                    {
                        integerType = FormattedPartType.Fraction;
                    }
                    else if (type == FormattedPartType.ExponentSeparator)
                    {
                        integerType = FormattedPartType.ExponentInteger;
                    }
                }
                subParts.Add(new FormattedPart(type, str));
            }
            numParts.RemoveAt(index);
            numParts.InsertRange(index, subParts);

            // format as curreny or unit with the formatted number
            List <FormattedPart> finalParts = new List <FormattedPart>(styleFormat);

            index = finalParts.FindIndex(v => v.Type == FormattedPartType.Placeholder);
            finalParts.RemoveAt(index);
            finalParts.InsertRange(index, numParts);
            return(new FormattedString(finalParts));
        }
        public void AdjustValueStepTests(decimal min, decimal max, decimal?step, RoundingType roundingType, decimal input, decimal expected)
        {
            var result = ExchangeHelpers.AdjustValueStep(min, max, step, roundingType, input);

            Assert.AreEqual(expected, result);
        }
Exemplo n.º 31
0
 /// <summary>
 /// Sets the <see cref="RoundBy"/>.
 /// </summary>
 /// <param name="index">The index of the <see cref="RoundingType"/>.</param>
 public virtual void SetRoundBy(int index)
 {
     RoundBy = EnumExtensions.GetByIndex <RoundingType>(index);
 }
Exemplo n.º 32
0
 public PBNumber(PBPrototype inNumberPrototype, NumberCapacity inCapacity, RoundingType inRounding)
     : this(inCapacity, inNumberPrototype.Sign, inNumberPrototype.Exponent, inNumberPrototype.Mantissa, inRounding)
 {
     if (pbConvertion == null)
         pbConvertion = new PBConvertion();
 }
 public StepRoundingToken(StepMultiplierToken parent, RoundingType rounding)
     : base(parent)
 {
     this.Rounding = rounding;
 }
Exemplo n.º 34
0
        /// <summary>
        /// Round
        /// </summary>
        /// <param name="value">Value to round</param>
        /// <param name="roundingType">The rounding type</param>
        /// <returns>Rounded value</returns>
        public static decimal Round(this decimal value, RoundingType roundingType, MidpointRounding midpointRounding)
        {
            //default round (Rounding001)
            var rez          = Math.Round(value, 2, midpointRounding);
            var fractionPart = (rez - Math.Truncate(rez)) * 10;

            //cash rounding not needed
            if (fractionPart == 0)
            {
                return(rez);
            }

            //Cash rounding (details: https://en.wikipedia.org/wiki/Cash_rounding)
            switch (roundingType)
            {
            //rounding with 0.05 or 5 intervals
            case RoundingType.Rounding005Up:
            case RoundingType.Rounding005Down:
                fractionPart = (fractionPart - Math.Truncate(fractionPart)) * 10;
                if (fractionPart == 5 || fractionPart == 0)
                {
                    break;
                }
                if (roundingType == RoundingType.Rounding005Down)
                {
                    fractionPart = fractionPart > 5 ? 5 - fractionPart : fractionPart * -1;
                }
                else
                {
                    fractionPart = fractionPart > 5 ? 10 - fractionPart : 5 - fractionPart;
                }

                rez += fractionPart / 100;
                break;

            //rounding with 0.10 intervals
            case RoundingType.Rounding01Up:
            case RoundingType.Rounding01Down:
                fractionPart = (fractionPart - Math.Truncate(fractionPart)) * 10;
                if (fractionPart == 0)
                {
                    break;
                }

                if (roundingType == RoundingType.Rounding01Down && fractionPart == 5)
                {
                    fractionPart = -5;
                }
                else
                {
                    fractionPart = fractionPart < 5 ? fractionPart * -1 : 10 - fractionPart;
                }

                rez += fractionPart / 100;
                break;

            //rounding with 0.50 intervals
            case RoundingType.Rounding05:
                fractionPart *= 10;
                fractionPart  = fractionPart < 25 ? fractionPart * -1 : fractionPart < 50 || fractionPart < 75 ? 50 - fractionPart : 100 - fractionPart;

                rez += fractionPart / 100;
                break;

            //rounding with 1.00 intervals
            case RoundingType.Rounding1:
            case RoundingType.Rounding1Up:
                fractionPart *= 10;

                if (roundingType == RoundingType.Rounding1Up && fractionPart > 0)
                {
                    rez = Math.Truncate(rez) + 1;
                }
                else
                {
                    rez = fractionPart < 50 ? Math.Truncate(rez) : Math.Truncate(rez) + 1;
                }

                break;

            case RoundingType.Rounding001:
            default:
                break;
            }

            return(rez);
        }
Exemplo n.º 35
0
        /// <summary>
        /// Adjust a value to be between the min and max parameters and rounded to the closest precision.
        /// </summary>
        /// <param name="min">The min value</param>
        /// <param name="max">The max value</param>
        /// <param name="precision">The precision the value should be rounded to. For example, value 2.554215 with a precision of 5 will output 2.5542</param>
        /// <param name="roundingType">How to round</param>
        /// <param name="value">The input value</param>
        /// <returns></returns>
        public static decimal AdjustValuePrecision(decimal min, decimal max, int?precision, RoundingType roundingType, decimal value)
        {
            value = Math.Min(max, value);
            value = Math.Max(min, value);
            if (precision == null)
            {
                return(value);
            }

            return(RoundToSignificantDigits(value, precision.Value, roundingType));
        }
Exemplo n.º 36
0
        /// <summary>
        /// Round
        /// </summary>
        /// <param name="value">Value to round</param>
        /// <param name="roundingType">The rounding type</param>
        /// <returns>Rounded value</returns>
        public static decimal Round(this decimal value, RoundingType roundingType)
        {
            //default round (Rounding001)
            var     rez = Math.Round(value, 2);
            decimal t;

            //Cash rounding (details: https://en.wikipedia.org/wiki/Cash_rounding)
            switch (roundingType)
            {
            //rounding with 0.05 or 5 intervals
            case RoundingType.Rounding005Up:
            case RoundingType.Rounding005Down:
                t = (rez - Math.Truncate(rez)) * 10;
                t = (t - Math.Truncate(t)) * 10;

                if (roundingType == RoundingType.Rounding005Down)
                {
                    t = t >= 5 ? 5 - t : t * -1;
                }
                else
                {
                    t = t >= 5 ? 10 - t : 5 - t;
                }

                rez += t / 100;
                break;

            //rounding with 0.10 intervals
            case RoundingType.Rounding01Up:
            case RoundingType.Rounding01Down:
                t = (rez - Math.Truncate(rez)) * 10;
                t = (t - Math.Truncate(t)) * 10;

                if (roundingType == RoundingType.Rounding01Down && t == 5)
                {
                    t = -5;
                }
                else
                {
                    t = t < 5 ? t * -1 : 10 - t;
                }

                rez += t / 100;
                break;

            //rounding with 0.50 intervals
            case RoundingType.Rounding05:
                t = (rez - Math.Truncate(rez)) * 100;
                t = t < 25 ? t * -1 : t < 50 || t < 75 ? 50 - t : 100 - t;

                rez += t / 100;
                break;

            //rounding with 1.00 intervals
            case RoundingType.Rounding1:
            case RoundingType.Rounding1Up:
                t = (rez - Math.Truncate(rez)) * 100;

                if (roundingType == RoundingType.Rounding1Up && t > 0)
                {
                    rez = Math.Truncate(rez) + 1;
                }
                else
                {
                    rez = t < 50 ? Math.Truncate(rez) : Math.Truncate(rez) + 1;
                }

                break;

            case RoundingType.Rounding001:
            default:
                break;
            }

            return(rez);
        }
        public static Expression RoundExpression(Expression value, decimal multiplier, RoundingType rounding)
        {
            var result = value;

            result = result.Type.UnNullify() == typeof(decimal) ?
                result.UnNullify() :
                Expression.Convert(result, typeof(double));

            if (rounding == RoundingType.RoundMiddle)
                result = Expression.Subtract(result, Constant(multiplier / 2, result.Type));

            if (multiplier != 1)
                result = Expression.Divide(result, Constant(multiplier, result.Type));

            if (rounding == RoundingType.Ceil)
                result = result.Type.UnNullify() == typeof(decimal) ?
                    Expression.Call(miCeilingDecimal, result.UnNullify()) :
                    Expression.Call(miCeilingDouble, result.TryConvert(typeof(double)));
            else if (rounding == RoundingType.Floor)
                result = result.Type.UnNullify() == typeof(decimal) ?
                    Expression.Call(miFloorDecimal, result.UnNullify()) :
                    Expression.Call(miFloorDouble, result.TryConvert(typeof(double)));
            else if (rounding == RoundingType.Round || rounding == RoundingType.RoundMiddle)
                result = result.Type.UnNullify() == typeof(decimal) ?
                    Expression.Call(miRoundDecimal, result.UnNullify()) :
                    Expression.Call(miRoundDouble, result.TryConvert(typeof(double)));

            if (multiplier != 1)
                result = Expression.Multiply(result, Constant(multiplier, result.Type));

            if (rounding == RoundingType.RoundMiddle)
                result = Expression.Add(result, Constant(multiplier / 2, result.Type));

            return result.Nullify().TryConvert(value.Type.Nullify());
        }