Exemple #1
0
        internal static Point LayoutRound(Point point, RoundingMode roundingMode)
        {
            point.X = LayoutUtils.RoundX(point.X, roundingMode);
            point.Y = LayoutUtils.RoundY(point.Y, roundingMode);

            return(point);
        }
        public static RoundingStrategy GetRoundingStrategy(RoundingMode roundingMode)
        {
            switch (roundingMode)
            {
            case RoundingMode.HalfAwayFromZero:
            {
                return(new HalfAwayFromZero());
            }

            case RoundingMode.HalfToEven:
            {
                return(new HalfToEven());
            }

            case RoundingMode.HalfToOdd:
            {
                return(new HalfToOdd());
            }

            case RoundingMode.HalfTowardZero:
            {
                return(new HalfTowardZero());
            }
            }
            throw new NotImplementedException();
        }
Exemple #3
0
        internal static double Round(double value, int digits, RoundingMode mode)
        {
            if (Math.Abs(value) < DoubleRoundLimit == false)
            {
                return(value);
            }

            if (mode == RoundingMode.MidPointToEven)
            {
                return(Math.Round(value, digits, MidpointRounding.ToEven));
            }

            var power10 = RoundPower10Double[digits];

            value *= power10;

            var fractional = SplitFractional(ref value);

            if (mode == RoundingMode.ToZero)
            {
                return(value / power10);
            }

            if (mode == RoundingMode.FromZero || Math.Abs(fractional) >= 0.5)
            {
                value += Math.Sign(fractional);
            }

            value /= power10;

            return(value);
        }
Exemple #4
0
        private static int getangle(float angle, int quad, int dist, RoundingMode rmode, int tsize)
        {
            int    tgtPoint  = tsize * dist;
            double unrounded = 0;

            if (quad == 0 || quad == 7 || quad == 3 || quad == 4)
            {
                unrounded = (double)tgtPoint * Math.Tan(angle);
            }
            else
            {
                unrounded = (double)tgtPoint / Math.Tan(angle);
            }

            switch (rmode)
            {
            case RoundingMode.Up:
                return((int)Math.Ceiling(unrounded / (double)tsize));

            case RoundingMode.Down:
                return((int)Math.Floor(unrounded / (double)tsize));

            case RoundingMode.Nearest:
            default:
                return((int)Math.Round(unrounded / (double)tsize));
            }
        }
Exemple #5
0
        public RationalHandle Round(RationalHandle u, int decimals, RoundingMode mode)
        {
            var native_mode = (Int32)mode;

            HandleResultCode((PMC_STATUS_CODE)PMCCS_Round_R_I(u.NativeHandle, decimals, native_mode, out IntPtr w));
            return(new RationalHandle(w));
        }
Exemple #6
0
        public BigIntHandle Round(RationalHandle u, RoundingMode mode)
        {
            var native_mode = (Int32)mode;

            HandleResultCode((PMC_STATUS_CODE)PMCCS_Round_R(u.NativeHandle, native_mode, out IntPtr w));
            return(new BigIntHandle(w));
        }
        public static BigDecimal Scale(BigDecimal number, int newScale, RoundingMode roundingMode)
        {
            long diffScale = newScale - (long)number.Scale;

            // Let be:  'number' = [u,s]
            if (diffScale == 0)
            {
                return(number);
            }
            if (diffScale > 0)
            {
                // return  [u * 10^(s2 - s), newScale]
                if (diffScale < BigDecimal.LongTenPow.Length &&
                    (number.BitLength + BigDecimal.LongTenPowBitLength[(int)diffScale]) < 64)
                {
                    return(BigDecimal.Create(number.SmallValue * BigDecimal.LongTenPow[(int)diffScale], newScale));
                }
                return(new BigDecimal(Multiplication.MultiplyByTenPow(number.UnscaledValue, (int)diffScale), newScale));
            }
            // diffScale < 0
            // return  [u,s] / [1,newScale]  with the appropriate scale and rounding
            if (number.BitLength < 64 && -diffScale < BigDecimal.LongTenPow.Length)
            {
                return(DividePrimitiveLongs(number.SmallValue, BigDecimal.LongTenPow[(int)-diffScale], newScale, roundingMode));
            }

            return(DivideBigIntegers(number.UnscaledValue, Multiplication.PowerOf10(-diffScale), newScale, roundingMode));
        }
Exemple #8
0
        public static int ordinal(RoundingMode mode)
        {
            switch (mode)
            {
            case RoundingMode.UP:
                return(0);

            case RoundingMode.DOWN:
                return(1);

            case RoundingMode.CEILING:
                return(2);

            case RoundingMode.FLOOR:
                return(3);

            case RoundingMode.HALF_UP:
                return(4);

            case RoundingMode.HALF_DOWN:
                return(5);

            case RoundingMode.HALF_EVEN:
                return(6);

            case RoundingMode.UNNECESSARY:
                return(7);

            default:
                throw new System.ArgumentException("Invalid rounding mode");
            }
        }
Exemple #9
0
        internal static Point Round(Point point, RoundingMode roundingMode, int digits = 0)
        {
            point.X = Math.Round(point.X, digits);
            point.Y = Math.Round(point.Y, digits);

            return(point);
        }
Exemple #10
0
        public static decimal Round(decimal value, int decimalPlaces, RoundingMode mode)
        {
            // Rounding modes defined in IEEE 754. Unsurprisingly, .NET provides native support for them.
            switch (mode)
            {
            case RoundingMode.Down: return(Down(value, decimalPlaces));

            case RoundingMode.Up: return(Up(value, decimalPlaces));

            case RoundingMode.TowardsZero: return(TowardsZero(value, decimalPlaces));

            case RoundingMode.HalfAwayFromZero: return(HalfAwayFromZero(value, decimalPlaces));

            case RoundingMode.ToEven: return(ToEven(value, decimalPlaces));
            }

            // Rounding modes not part of IEEE 754.
            switch (mode)
            {
            case RoundingMode.AwayFromZero: return(AwayFromZero(value, decimalPlaces));

            case RoundingMode.HalfDown: return(HalfDown(value, decimalPlaces));

            case RoundingMode.HalfUp: return(HalfUp(value, decimalPlaces));

            case RoundingMode.HalfTowardsZero: return(HalfTowardsZero(value, decimalPlaces));

            case RoundingMode.ToOdd: return(ToOdd(value, decimalPlaces));

            default: throw new ControlFlowException();
            }
        }
Exemple #11
0
        public void Round_no_arguments_using_Money_defaults(RoundingMode roundingMode, DecimalPlaces decimalPlaces, decimal value, decimal expected)
        {
            Money money  = new Money("ZAR", value, roundingMode, decimalPlaces);
            Money actual = money.Round();

            Assert.That(actual.Amount == expected);
        }
        public static CartDraft DefaultCartDraftWithTaxRoundingMode(CartDraft draft, RoundingMode roundingMode)
        {
            var cartDraft = DefaultCartDraft(draft);

            cartDraft.TaxRoundingMode = roundingMode;
            return(cartDraft);
        }
Exemple #13
0
        internal static Size Round(Size size, RoundingMode roundingMode, int digits = 0)
        {
            var width  = DoubleUtils.Round(size.Width, digits, roundingMode);
            var height = DoubleUtils.Round(size.Height, digits, roundingMode);

            return(new Size(width, height));
        }
Exemple #14
0
 public Money(Currency currency, decimal amount, RoundingMode roundingMode, DecimalPlaces decimalPlaces)
 {
     Currency      = currency;
     Amount        = amount;
     RoundingMode  = roundingMode;
     DecimalPlaces = (int)decimalPlaces;
 }
Exemple #15
0
        public BigFloat Divide(BigFloat divisor, int scale, RoundingMode mode)
        {
            BigFloat foo = this.Divide(divisor);
            BigFloat ret = foo.setScale(scale, mode);

            return(ret);
        }
Exemple #16
0
        internal static Size LayoutRound(Size size, RoundingMode roundingMode)
        {
            var width  = LayoutUtils.RoundX(size.Width, roundingMode);
            var height = LayoutUtils.RoundY(size.Height, roundingMode);

            return(new Size(width, height));
        }
Exemple #17
0
        /////////////////////////////////////////////////////////////////////////////////////

        public bool Visit(VCExprLiteral node, LineariserOptions options)
        {
            if (node == VCExpressionGenerator.True)
            {
                wr.Write("true");
            }
            else if (node == VCExpressionGenerator.False)
            {
                wr.Write("false");
            }
            else if (node is VCExprIntLit)
            {
                BigNum lit = ((VCExprIntLit)node).Val;
                if (lit.IsNegative)
                {
                    // In SMT2 "-42" is an identifier (SMT2, Sect. 3.2 "Symbols")
                    wr.Write("(- 0 {0})", lit.Abs);
                }
                else
                {
                    wr.Write(lit);
                }
            }
            else if (node is VCExprRealLit)
            {
                BigDec lit = ((VCExprRealLit)node).Val;
                if (lit.IsNegative)
                {
                    // In SMT2 "-42" is an identifier (SMT2, Sect. 3.2 "Symbols")
                    wr.Write("(- 0.0 {0})", lit.Abs.ToDecimalString());
                }
                else
                {
                    wr.Write(lit.ToDecimalString());
                }
            }
            else if (node is VCExprFloatLit)
            {
                BigFloat lit = ((VCExprFloatLit)node).Val;
                wr.Write("(" + lit.ToBVString() + ")");
            }
            else if (node is VCExprRModeLit)
            {
                RoundingMode lit = ((VCExprRModeLit)node).Val;
                wr.Write(lit.ToString());
            }
            else if (node is VCExprStringLit)
            {
                String lit = ((VCExprStringLit)node).Val;
                wr.Write("\"" + lit.ToString() + "\"");
            }
            else
            {
                Contract.Assert(false);
                throw new cce.UnreachableException();
            }

            return(true);
        }
Exemple #18
0
 private HNumber(BigInteger mantissa, int exponent, int precision, RoundingMode roundingMode)
 {
     Mantissa   = mantissa;
     Exponent   = Mantissa.IsZero ? 0 : exponent;
     DigitCount = CalculateDigitCount(Mantissa);
     Precision  = precision;
     Round(roundingMode);
 }
Exemple #19
0
 public BigDecimal SetScale(int scale, RoundingMode roundingMode)
 {
     if (scale < 0)
     {
         throw new ArithmeticException("Scale parameter < 0");
     }
     return(Divide(One, scale, roundingMode));
 }
        public void Round_DecimalPlaces_using_Money_RoundingMode(RoundingMode roundingMode, DecimalPlaces decimalPlaces, decimal value, decimal expected)
        {
            // specify different DecimalPlaces for Money ctor to ensure the argument value is used
            Money money = new Money("ZAR", value, roundingMode, DecimalPlaces.Nine);

            Money actual = money.Round(decimalPlaces);
            Assert.That(actual.Amount == expected);
        }
Exemple #21
0
            public static @string String(this RoundingMode i)
            {
                if (i >= RoundingMode(len(_RoundingMode_index) - 1L))
                {
                    return("RoundingMode(" + strconv.FormatInt(int64(i), 10L) + ")");
                }

                return(_RoundingMode_name[_RoundingMode_index[i].._RoundingMode_index[i + 1L]]);
Exemple #22
0
 public MathContext(int precision, RoundingMode roundingMode)
 {
     if (precision < 0)
     {
         throw new ArgumentException("Precision cannot be less than zero");
     }
     mPrecision    = precision;
     mRoundingMode = roundingMode;
 }
Exemple #23
0
        /**
         * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
         * The scale of the result is the scale of {@code this}. If rounding is
         * required to meet the specified scale, then the specified rounding mode
         * {@code roundingMode} is applied.
         *
         * @param divisor
         *            value by which {@code this} is divided.
         * @param roundingMode
         *            rounding mode to be used to round the result.
         * @return {@code this / divisor} rounded according to the given rounding
         *         mode.
         * @throws NullPointerException
         *             if {@code divisor == null} or {@code roundingMode == null}.
         * @throws ArithmeticException
         *             if {@code divisor == 0}.
         * @throws ArithmeticException
         *             if {@code roundingMode == RoundingMode.UNNECESSARY} and
         *             rounding is necessary according to the scale of this.
         */
        public static BigDecimal Divide(BigDecimal a, BigDecimal b, RoundingMode roundingMode)
        {
            if (!Enum.IsDefined(typeof(RoundingMode), roundingMode))
            {
                throw new ArgumentException();
            }

            return(Divide(a, b, a.Scale, roundingMode));
        }
 public void AddWithContext(string a, int aScale, string b, int bScale, string c, int cScale, int precision, RoundingMode mode)
 {
     BigDecimal aNumber = new BigDecimal(BigInteger.Parse(a), aScale);
     BigDecimal bNumber = new BigDecimal(BigInteger.Parse(b), bScale);
     MathContext mc = new MathContext(precision, mode);
     BigDecimal result = aNumber.Add(bNumber, mc);
     Assert.AreEqual(c, result.ToString(), "incorrect value");
     Assert.AreEqual(cScale, result.Scale, "incorrect scale");
 }
Exemple #25
0
        public void Round_DecimalPlaces_using_Money_RoundingMode(RoundingMode roundingMode, DecimalPlaces decimalPlaces, decimal value, decimal expected)
        {
            // specify different DecimalPlaces for Money ctor to ensure the argument value is used
            Money money = new Money("ZAR", value, roundingMode, DecimalPlaces.Nine);

            Money actual = money.Round(decimalPlaces);

            Assert.That(actual.Amount == expected);
        }
Exemple #26
0
 public MathContext(int precision, RoundingMode roundingMode)
 {
     if (precision < 0)
     {
         throw new System.ArgumentException("Digits < 0");
     }
     this.precision    = precision;
     this.roundingMode = roundingMode;
 }
Exemple #27
0
        /**
         * Returns a new {@code BigDecimal} instance with the specified scale.
         * <p>
         * If the new scale is greater than the old scale, then additional zeros are
         * added to the unscaled value. In this case no rounding is necessary.
         * <p>
         * If the new scale is smaller than the old scale, then trailing digits are
         * removed. If these trailing digits are not zero, then the remaining
         * unscaled value has to be rounded. For this rounding operation the
         * specified rounding mode is used.
         *
         * @param newScale
         *            scale of the result returned.
         * @param roundingMode
         *            rounding mode to be used to round the result.
         * @return a new {@code BigDecimal} instance with the specified scale.
         * @throws NullPointerException
         *             if {@code roundingMode == null}.
         * @throws ArithmeticException
         *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
         *             necessary according to the given scale.
         */

        public static BigDecimal Scale(BigDecimal number, int newScale, RoundingMode roundingMode)
        {
            if (!Enum.IsDefined(typeof(RoundingMode), roundingMode))
            {
                throw new ArgumentException();
            }

            return(BigDecimalMath.Scale(number, newScale, roundingMode));
        }
        public void Round_RoundingMode_using_Money_DecimalPlaces(RoundingMode roundingMode, DecimalPlaces decimalPlaces, decimal value, decimal expected)
        {
            // specify different RoundingMode for Money ctor to ensure the argument value is used
            RoundingMode moneyMode = roundingMode == 0 ? roundingMode + 1 : roundingMode - 1;
            Money money = new Money("ZAR", value, moneyMode, decimalPlaces);

            Money actual = money.Round(roundingMode);
            Assert.That(actual.Amount == expected);
        }
Exemple #29
0
        public Number SetScale(int d, RoundingMode rounding)
        {
            if (numberState == NumberState.None)
            {
                return(new Number(NumberState.None, bigDecimal.SetScale(d, rounding)));
            }

            // Can't round -inf, +inf and NaN
            return(this);
        }
 /// <summary>
 ///  Constructs a new <see cref="MathContext"/> with the specified precision and with the
 /// specified rounding mode.
 /// </summary>
 /// <param name="precision">The precision for the new context.</param>
 /// <param name="roundingMode">The rounding mode for the new context.</param>
 /// <remarks>
 /// If the precision passed is zero, then this implies that the computations have to
 /// be performed exact, the rounding mode in this case is irrelevant.
 /// </remarks>
 /// <exception cref="ArgumentException">
 /// If <paramref name="precision"/> is smaller than zero.
 /// </exception>
 public MathContext(int precision, RoundingMode roundingMode)
 {
     if (precision < 0)
     {
         // math.0C=Digits < 0
         throw new ArgumentException(Messages.math0C);                 //$NON-NLS-1$
     }
     this.precision    = precision;
     this.roundingMode = roundingMode;
 }
Exemple #31
0
        public SqlNumber SetScale(int scale, RoundingMode mode)
        {
            if (State == NumericState.None)
            {
                return(new SqlNumber(innerValue.SetScale(scale, mode)));
            }

            // Can't round -inf, +inf and NaN
            return(this);
        }
Exemple #32
0
        public void Round_RoundingMode_using_Money_DecimalPlaces(RoundingMode roundingMode, DecimalPlaces decimalPlaces, decimal value, decimal expected)
        {
            // specify different RoundingMode for Money ctor to ensure the argument value is used
            RoundingMode moneyMode = roundingMode == 0 ? roundingMode + 1 : roundingMode - 1;
            Money        money     = new Money("ZAR", value, moneyMode, decimalPlaces);

            Money actual = money.Round(roundingMode);

            Assert.That(actual.Amount == expected);
        }
Exemple #33
0
 public Float(uint prec = default, RoundingMode mode = default, Accuracy acc = default, form form = default, bool neg = default, nat mant = default, int exp = default)
 {
     this.prec = prec;
     this.mode = mode;
     this.acc  = acc;
     this.form = form;
     this.neg  = neg;
     this.mant = mant;
     this.exp  = exp;
 }
 public static RoundingStrategy GetRoundingStrategy(RoundingMode roundingMode)
 {
     switch (roundingMode)
     {
         case RoundingMode.HalfAwayFromZero:
             {
                 return new HalfAwayFromZero();
             }
         case RoundingMode.HalfToEven:
             {
                 return new HalfToEven();
             }
         case RoundingMode.HalfToOdd:
             {
                 return new HalfToOdd();
             }
         case RoundingMode.HalfTowardZero:
             {
                 return new HalfTowardZero();
             }
     }
     throw new NotImplementedException();
 }
Exemple #35
0
 public static int ordinal(RoundingMode mode)
 {
     switch (mode) {
     case RoundingMode.UP:
         return 0;
     case RoundingMode.DOWN:
         return 1;
     case RoundingMode.CEILING:
         return 2;
     case RoundingMode.FLOOR:
         return 3;
     case RoundingMode.HALF_UP:
         return 4;
     case RoundingMode.HALF_DOWN:
         return 5;
     case RoundingMode.HALF_EVEN:
         return 6;
     case RoundingMode.UNNECESSARY:
         return 7;
     default:
         throw new System.ArgumentException("Invalid rounding mode");
     }
 }
 private static IEnumerable<KeyValuePair<decimal, decimal>> GetTestCaseDictionary(RoundingMode roundingMode)
 {
     switch (roundingMode)
     {
         case RoundingMode.HalfAwayFromZero:
             {
                 return HalfAwayFromZeroTestCases.extensionMethodCases;
             }
         case RoundingMode.HalfToEven:
             {
                 return HalfToEvenTestCases.extensionMethodCases;
             }
         case RoundingMode.HalfToOdd:
             {
                 return HalfToOddTestCases.extensionMethodCases;
             }
         case RoundingMode.HalfTowardZero:
             {
                 return HalfTowardZeroTestCases.extensionMethodCases;
             }
     }
     return null;
 }
Exemple #37
0
 public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode)
 {
     return divide(divisor, _scale, roundingMode);
 }
 public void Round_no_arguments_using_Money_defaults(RoundingMode roundingMode, DecimalPlaces decimalPlaces, decimal value, decimal expected)
 {
     Money money = new Money("ZAR", value, roundingMode, decimalPlaces);
     Money actual = money.Round();
     Assert.That(actual.Amount == expected);
 }
Exemple #39
0
 public static extern int imaqConvolve2(IntPtr dest, IntPtr source, ref float kernel, int matrixRows, int matrixCols, float normalize, IntPtr mask, RoundingMode roundingMode);
Exemple #40
0
 public MathContext(int arg0, RoundingMode arg1)
     : base(ProxyCtor.I)
 {
     Instance.CallConstructor("(ILjava/math/RoundingMode;)V", arg0, arg1);
 }
Exemple #41
0
        private static int roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode)
        {
            int increment = 0; // the carry after rounding

            switch (roundingMode) {
            case RoundingMode.UNNECESSARY:
                if (fraction != 0) {
                    throw new ArithmeticException("Rounding necessary");
                }
                break;
            case RoundingMode.UP:
                increment = Math.Sign(fraction);
                break;
            case RoundingMode.DOWN:
                break;
            case RoundingMode.CEILING:
                increment = Math.Max(Math.Sign(fraction), 0);
                break;
            case RoundingMode.FLOOR:
                increment = Math.Min(Math.Sign(fraction), 0);
                break;
            case RoundingMode.HALF_UP:
                if (Math.Abs(fraction) >= 5) {
                    increment = Math.Sign(fraction);
                }
                break;
            case RoundingMode.HALF_DOWN:
                if (Math.Abs(fraction) > 5) {
                    increment = Math.Sign(fraction);
                }
                break;
            case RoundingMode.HALF_EVEN:
                if (Math.Abs(fraction) + parityBit > 5) {
                    increment = Math.Sign(fraction);
                }
                break;
            }
            return increment;
        }
 /// <summary>
 /// コンストラクタ
 /// </summary>
 public ValueToIntConverter()
 {
     RoundingMode = RoundingMode.Floor;
 }
	  /**
	   * Constructs a MathContext from a String that has the same form as one
	   * produced by the toString() method.
	   * @param val
	   * 
	   * @throws IllegalArgumentException if the String is not in the correct
	   * format or if the precision specified is < 0.
	   */
	  public MathContext(String val)
	  {
	    try
	    {
	      int roundingModeIndex = val.IndexOf("roundingMode", 10);
	      precision = Int32.Parse(val.Substring(10, roundingModeIndex - 1));
		  //TODO: Determine what the logic of the subscring passed to an int parameter without explicit conversion
	      roundMode = RoundingModes.valueOf(Int32.Parse (val.Substring(roundingModeIndex + 13)));
	    }
	    catch (FormatException nfe)
	    {
	      throw new ArgumentException("String not in correct format", nfe);
	    }
	    catch (ArgumentException iae)
	    {
	      throw new ArgumentException("String not in correct format", iae);
	    }
	    if (precision < 0)
	      throw new ArgumentException("Precision cannot be less than 0.");
	  }
Exemple #44
0
 public BigDecimal setScale(int newScale, RoundingMode roundingMode)
 {
     long diffScale = newScale - (long)_scale;
     // Let be:  'this' = [u,s]
     if(diffScale == 0) {
         return this;
     }
     if(diffScale > 0) {
         // return  [u * 10^(s2 - s), newScale]
         if(diffScale < LONG_TEN_POW.Length &&
            (this._bitLength + LONG_TEN_POW_BIT_LENGTH[(int)diffScale]) < 64 ) {
             return valueOf(this.smallValue*LONG_TEN_POW[(int)diffScale],newScale);
         }
         return new BigDecimal(Multiplication.multiplyByTenPow(getUnscaledValue(),(int)diffScale), newScale);
     }
     // diffScale < 0
     // return  [u,s] / [1,newScale]  with the appropriate scale and rounding
     if(this._bitLength < 64 && -diffScale < LONG_TEN_POW.Length) {
         return dividePrimitiveLongs(this.smallValue, LONG_TEN_POW[(int)-diffScale], newScale,roundingMode);
     }
     return divideBigIntegers(this.getUnscaledValue(),Multiplication.powerOf10(-diffScale),newScale,roundingMode);
 }
        public static Money Round(this Money money, RoundingMode roundingMode, DecimalPlaces decimalPlaces)
        {
            RoundingStrategy strategy = RoundingStrategyFactory.GetRoundingStrategy(roundingMode);

            return strategy.Round(money, (int) decimalPlaces);
        }
Exemple #46
0
 public void setRoundingMode(RoundingMode arg0)
 {
     Instance.CallMethod("setRoundingMode", "(Ljava/math/RoundingMode;)V", arg0);
 }
Exemple #47
0
 /// <summary>
 /// Limits the nmber of significant digits.
 /// </summary>
 /// <param name="r">The value.</param>
 /// <param name="nrDigits">The number of significant digits.</param>
 /// <param name="roundingMode">The mode the value is rounded.</param>
 /// <returns></returns>
 public static double LimitSignificantDigits(double r, int nrDigits, RoundingMode roundingMode = RoundingMode.Nearest)
 {
     if (r != 0)
       {
     int exponent = (int)Math.Truncate(Math.Log10(Math.Abs(r)));
     double mantissa = r / (Math.Pow(10, exponent));
     int nrDig;
     if (Math.Abs(mantissa) < 1d)
       nrDig = nrDigits;
     else
       nrDig = nrDigits - 1;
     switch (roundingMode)
     {
       case RoundingMode.Nearest:
     mantissa = Math.Round(mantissa * Math.Pow(10, nrDig));
     break;
       case RoundingMode.Up:
     mantissa = Math.Ceiling(mantissa * Math.Pow(10, nrDig));
     break;
       case RoundingMode.Down:
     mantissa = Math.Floor(mantissa * Math.Pow(10, nrDig));
     break;
       case RoundingMode.Truncate:
     mantissa = Math.Truncate(mantissa * Math.Pow(10, nrDig));
     break;
       default:
     break;
     }
     return mantissa / Math.Pow(10, nrDig - exponent);
       }
       return 0;
 }
Exemple #48
0
 ///<summary>
 ///</summary>
 ///<param name="d"></param>
 ///<param name="round_enum"></param>
 ///<returns></returns>
 public BigNumber SetScale(int d, RoundingMode round_enum)
 {
     if (numberState == 0) {
         return new BigNumber(NumberState.None, bigDecimal.SetScale(d, round_enum));
     }
     // Can't round -inf, +inf and NaN
     return this;
 }
Exemple #49
0
        public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
        {
            // Let be: this = [u1,s1]  and  divisor = [u2,s2]
            if (divisor.isZero()) {
                throw new ArithmeticException("Division by zero");
            }

            long diffScale = ((long)this._scale - divisor._scale) - scale;
            if(this._bitLength < 64 && divisor._bitLength < 64 ) {
                if(diffScale == 0) {
                    return dividePrimitiveLongs(this.smallValue,
                                                divisor.smallValue,
                                                scale,
                                                roundingMode );
                } else if(diffScale > 0) {
                    if(diffScale < LONG_TEN_POW.Length &&
                       divisor._bitLength + LONG_TEN_POW_BIT_LENGTH[(int)diffScale] < 64) {
                        return dividePrimitiveLongs(this.smallValue,
                                                    divisor.smallValue*LONG_TEN_POW[(int)diffScale],
                                                    _scale,
                                                    roundingMode);
                    }
                } else { // diffScale < 0
                    if(-diffScale < LONG_TEN_POW.Length &&
                       this._bitLength + LONG_TEN_POW_BIT_LENGTH[(int)-diffScale] < 64) {
                        return dividePrimitiveLongs(this.smallValue*LONG_TEN_POW[(int)-diffScale],
                                                    divisor.smallValue,
                                                    scale,
                                                    roundingMode);
                    }

                }
            }
            BigInteger scaledDividend = this.getUnscaledValue();
            BigInteger scaledDivisor = divisor.getUnscaledValue(); // for scaling of 'u2'

            if (diffScale > 0) {
                // Multiply 'u2'  by:  10^((s1 - s2) - scale)
                scaledDivisor = Multiplication.multiplyByTenPow(scaledDivisor, (int)diffScale);
            } else if (diffScale < 0) {
                // Multiply 'u1'  by:  10^(scale - (s1 - s2))
                scaledDividend  = Multiplication.multiplyByTenPow(scaledDividend, (int)-diffScale);
            }
            return divideBigIntegers(scaledDividend, scaledDivisor, scale, roundingMode);
        }
Exemple #50
0
 public static extern int imaqDivide2(IntPtr dest, IntPtr sourceA, IntPtr sourceB, RoundingMode roundingMode);
	  /**
	   * Constructs a new MathContext with the specified precision and rounding
	   * mode.
	   * @param setPrecision the precision
	   * @param setRoundingMode the rounding mode
	   * 
	   * @throws IllegalArgumentException if precision is < 0.
	   */
	  public MathContext(int setPrecision, RoundingMode setRoundingMode)
	  {
	    if (setPrecision < 0)
	      throw new ArgumentException("Precision cannot be less than zero.");
	    precision = setPrecision;
	    roundMode = setRoundingMode;
	  }
Exemple #52
0
        private static BigDecimal divideBigIntegers(BigInteger scaledDividend, BigInteger scaledDivisor, int scale, RoundingMode roundingMode)
        {
            BigInteger[] quotAndRem = scaledDividend.divideAndRemainder(scaledDivisor);  // quotient and remainder

            // If after division there is a remainder...
            BigInteger quotient = quotAndRem[0];
            BigInteger remainder = quotAndRem[1];
            if (remainder.signum() == 0) {
                return new BigDecimal(quotient, scale);
            }
            int sign = scaledDividend.signum() * scaledDivisor.signum();
            int compRem;                                      // 'compare to remainder'
            if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after <<1
                long rem = remainder.longValue();
                long divisor = scaledDivisor.longValue();
                compRem = longCompareTo(Math.Abs(rem) << 1,Math.Abs(divisor));
                // To look if there is a carry
                compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
                                           sign * (5 + compRem), roundingMode);

            } else {
                // Checking if:  remainder * 2 >= scaledDivisor
                compRem = remainder.abs().shiftLeftOneBit().compareTo(scaledDivisor.abs());
                compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
                                           sign * (5 + compRem), roundingMode);
            }
            if (compRem != 0) {
                if(quotient.bitLength() < 63) {
                    return valueOf(quotient.longValue() + compRem,scale);
                }
                quotient = quotient.add(BigInteger.valueOf(compRem));
                return new BigDecimal(quotient, scale);
            }
            // Constructing the result with the appropriate unscaled value
            return new BigDecimal(quotient, scale);
        }
Exemple #53
0
 private static BigDecimal dividePrimitiveLongs(long scaledDividend, long scaledDivisor, int scale, RoundingMode roundingMode)
 {
     long quotient = scaledDividend / scaledDivisor;
     long remainder = scaledDividend % scaledDivisor;
     int sign = Math.Sign( scaledDividend ) * Math.Sign( scaledDivisor );
     if (remainder != 0) {
         // Checking if:  remainder * 2 >= scaledDivisor
         int compRem;                                      // 'compare to remainder'
         compRem = longCompareTo(Math.Abs(remainder) << 1,Math.Abs(scaledDivisor));
         // To look if there is a carry
         quotient += roundingBehavior(((int)quotient) & 1,
                                      sign * (5 + compRem),
                                      roundingMode);
     }
     // Constructing the result with the appropriate unscaled value
     return valueOf(quotient, scale);
 }
Exemple #54
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 public UIntCalcExtension(string expression, RoundingMode mode)
 {
     Mode = mode;
     Expression = expression;
 }
 public static Money Round(this Money money, RoundingMode roundingMode)
 {
     return money.Round(roundingMode, (DecimalPlaces)money.DecimalPlaces);
 }
 /// <summary>
 /// Set the &lt;rounding-policy&gt; node of 
 ///&lt;merchant-checkout-flow-support&gt;
 /// </summary>
 /// <param name="mode">The <see cref="RoundingMode"/></param>
 /// <param name="rule">The <see cref="RoundingRule"/></param>
 public void SetRoundingPolicy(RoundingMode mode, RoundingRule rule)
 {
     _roundingRuleSet = true;
       _roundingMode = mode;
       _roundingRule = rule;
 }
 public void PowWithContext(string a, int aScale, int exp, string c, int cScale, int precision, RoundingMode roundingMode)
 {
     BigDecimal aNumber = new BigDecimal(BigInteger.Parse(a), aScale);
     MathContext mc = new MathContext(precision, roundingMode);
     BigDecimal result = aNumber.Pow(exp, mc);
     Assert.AreEqual(c, result.ToString(), "incorrect value");
     Assert.AreEqual(cScale, result.Scale, "incorrect scale");
 }