/// <summary> /// Initializes prices. /// </summary> void SetPrices() { initialPrice = Rounder.RoundToHundredth(initialPrice); resistancePrice = Rounder.RoundToHundredth(initialPrice * spread); supportPrice = Rounder.RoundToHundredth(initialPrice / spread); newSpread = resistancePrice - supportPrice; }
static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Black; float[,] map = new float[40, 40]; float[,] map2 = new float[40, 40]; map = Generator.PureRandom(40, 40, "asd"); map2 = Generator.PureRandom(40, 40, "aaa"); //map = GoniometricGenerator.sinWave(50, 50, 0.5f); map = TerrainMath.Multiply(map, 10); map = Smooth.SquareSmooth(map); map = Mountains.RemoveSmall(map, 6, 9); map = Water.RemoveSmall(map, 4, 7); map2 = TerrainMath.Multiply(map2, 10); map2 = Smooth.SquareSmooth(map); map2 = Mountains.RemoveSmall(map, 6, 9); map2 = Water.RemoveSmall(map, 4, 7); map = TerrainMath.Mix(map, map2); //map = TerrainMath.Clamp(map, 0, 9); map = Rounder.RoundDown(map); //map = Rounder.Round(map); VisualizeColor(map); Console.ReadLine(); }
/// <summary> /// /// </summary> /// /// <returns></returns> public Decimal[] GetTaxGroupAdjustments() { if (taxGroupAdjustments == null) { SalesDocument document = (SalesDocument)(this.Target); taxGroupAdjustments = new Decimal[Department.NUM_TAXGROUPS]; decimal productAdjustment, totalAdjustment = 0, maxAdjustment = 0; int maxAdjustedProduct = 0; foreach (int dep in document.TaxGroupTotals.Keys) { productAdjustment = Rounder.RoundDecimal(this.NetAmount * (document.TaxGroupTotals[dep] / this.adjustedTotal), 2, true); if (Math.Abs(productAdjustment) > Math.Abs(maxAdjustment)) { maxAdjustment = productAdjustment; maxAdjustedProduct = dep; } taxGroupAdjustments[dep] += productAdjustment; totalAdjustment += productAdjustment; } taxGroupAdjustments[maxAdjustedProduct] += this.NetAmount - totalAdjustment; } return(taxGroupAdjustments); }
public void Round(double num, int expected) { var rounder = new Rounder(); var result = Rounder.Round(num); Assert.Equal(expected, result); }
public void Normalise64bit() { int oldBitLen = _significand.BitLength(); int sc = oldBitLen - C_64; if (sc == 0) { return; } if (sc < 0) { throw new InvalidOperationException("Not enough precision"); } _binaryExponent += sc; if (sc > 32) { int highShift = (sc - 1) & 0xFFFFE0; _significand = _significand >> (highShift); sc -= highShift; oldBitLen -= highShift; } if (sc < 1) { throw new InvalidOperationException(); } _significand = Rounder.Round(_significand, sc); if (_significand.BitLength() > oldBitLen) { sc++; _binaryExponent++; } _significand = _significand >> (sc); }
public async Task <int> RateMovieAsync(int movieId, int userId, int rating) { if (rating < 1 || rating > 5) { throw new InvalidRatingException(rating); } var movieGetter = movieRepository.Get(movieId); var userGetter = userRepository.Get(userId); if (await movieGetter == null) { throw new MovieNotFoundException(movieId); } if (await userGetter == null) { throw new UserNotFoundException(userId); } var ratingSavedResult = await movieRatingRepository.UpsertAsync(new MovieRating { MovieId = movieId, UserId = userId, Rating = rating }); var ratings = await movieRatingRepository.GetByMovieId(movieId); var roundedAverageRating = Rounder.Round(ratings.Average(x => x.Rating)); return(await movieRepository.UpdateAverageRating(movieId, roundedAverageRating)); }
public void RoundNumbers() { var rounder = new Rounder(); rounder.RoundUp(1.64).ShouldBe(2.00); rounder.RoundDown(1.64).ShouldBe(1.00); rounder.Round(1.64).ShouldBe(2.00); }
public static double DoTheCalculation(double input1, double input2, Rounder rounder) { var intermediate1 = Math.Pow(input1, input2); // more calculations... var intermediate5 = rounder(intermediate1); // more calculations... var intermediate10 = Math.Abs(intermediate5); return(intermediate10); }
void UpdateCurrentPrice(float deltatime, int touchCount, bool lmbPressed) { if ((touchCount > 0 || lmbPressed) && currentPrice < resistancePrice + 0.3 && influence > 0) //Нужно подниматься чуть выше границы { currentPrice = Rounder.RoundToHundredth(currentPrice + currentPriceRiseSpeed * deltatime); //coin.posY * (1 / newSpread)= } else if (currentPrice > supportPrice - 0.3) //Нужно опускаться чуть ниже границы { currentPrice = Rounder.RoundToHundredth(currentPrice - currentPriceFallSpeed * deltatime); //coin.posY * (1 / newSpread) } }
public InventoryAssignmentModel(WorkEffortInventoryAssignment assignment) { this.PartId = assignment.InventoryItem.Part?.PartIdentification(); this.PartName = assignment.InventoryItem.Part?.Name; this.Quantity = assignment.DerivedBillableQuantity; this.UnitOfMeasure = assignment.InventoryItem.Part?.UnitOfMeasure?.Abbreviation?.ToUpperInvariant() ?? assignment.InventoryItem.Part?.UnitOfMeasure?.Name?.ToUpperInvariant() ?? "EA"; this.UnitSellingPrice = assignment.UnitSellingPrice.ToString("N2", new CultureInfo("nl-BE")); this.SellingPrice = Rounder.RoundDecimal(this.Quantity * assignment.UnitSellingPrice, 2).ToString("N2", new CultureInfo("nl-BE")); }
public PurchaseOrderItemAssignmentModel(WorkEffortPurchaseOrderItemAssignment assignment) { var purchaseOrderItem = assignment.PurchaseOrderItem; this.Name = purchaseOrderItem.Part?.Name ?? purchaseOrderItem.Description; this.Quantity = assignment.Quantity; this.UnitOfMeasure = purchaseOrderItem.Part?.UnitOfMeasure?.Abbreviation?.ToUpperInvariant() ?? purchaseOrderItem.Part?.UnitOfMeasure?.Name?.ToUpperInvariant() ?? "EA"; this.UnitSellingPrice = Rounder.RoundDecimal(assignment.UnitSellingPrice, 2).ToString("N2", new CultureInfo("nl-BE")); this.SellingPrice = Rounder.RoundDecimal(assignment.Quantity * assignment.UnitSellingPrice, 2).ToString("N2", new CultureInfo("nl-BE")); }
public static void PayByForeignCurrency(CurrencyPaymentInfo currency) { if (currency.Amount >= 10000000) { //Should probably be in document.pay cr.State = States.AlertCashier.Instance(new Confirm(PosMessage.CURRENCY_LIMIT_EXCEEDED_PAYMENT_INVALID)); return; } currency.Amount = Rounder.RoundDecimal(currency.Amount * currency.ExchangeRate, 2, true); //cr.State = cr.Document.Pay(currency); cr.State = CalculateTotal(currency); }
public TimeEntryByBillingRateModel(IGrouping <decimal?, TimeEntry> @group) { var timeEntries = @group.ToArray(); var billingRate = @group.Key ?? 0.0m; var amountOfTime = timeEntries.Where(v => v.IsBillable).Sum(v => v.BillableAmountOfTime ?? v.AmountOfTime ?? 0.0m); var billingAmount = timeEntries.Where(v => v.IsBillable).Sum(v => v.BillingAmount); var cost = timeEntries.Sum(v => v.Cost); // Round this.BillingRate = Rounder.RoundDecimal(billingRate, 2).ToString("N2", new CultureInfo("nl-BE")); this.AmountOfTime = Rounder.RoundDecimal(amountOfTime, 2).ToString("N2", new CultureInfo("nl-BE")); this.BillingAmount = Rounder.RoundDecimal(billingAmount, 2).ToString("N2", new CultureInfo("nl-BE")); this.Cost = Rounder.RoundDecimal(cost, 2).ToString("N2", new CultureInfo("nl-BE")); }
public TimeEntryModel(TimeEntry timeEntry) { var frequency = timeEntry.TimeFrequency?.Abbreviation ?? timeEntry.TimeFrequency?.Name; this.AmountOfTime = Rounder.RoundDecimal(timeEntry.BillableAmountOfTime ?? timeEntry.AmountOfTime ?? 0.0m, 2); this.BillingRate = Rounder.RoundDecimal(timeEntry.BillingRate ?? 0.0m, 2).ToString("N2", new CultureInfo("nl-BE")); this.BillingAmount = Rounder.RoundDecimal(timeEntry.BillingAmount, 2).ToString("N2", new CultureInfo("nl-BE")); this.Cost = Rounder.RoundDecimal(timeEntry.Cost, 2).ToString("N2", new CultureInfo("nl-BE")); this.TimeFrequency = frequency?.ToUpperInvariant(); this.WorkerName = timeEntry.TimeSheetWhereTimeEntry?.Worker?.PartyName; this.WorkerId = timeEntry.TimeSheetWhereTimeEntry?.Worker?.FirstName; this.Description = timeEntry.Description; this.IsBillable = timeEntry.IsBillable == true; this.FromDate = timeEntry.FromDate.ToString("yyyy-MM-dd"); this.FromTime = timeEntry.FromDate.ToString("hh:mm:ss"); this.ThroughDate = timeEntry.ThroughDate?.ToString("yyyy-MM-dd"); this.ThroughTime = timeEntry.ThroughDate?.ToString("hh:mm:ss"); }
public InvoiceItemModel(PurchaseInvoiceItem item) { this.Part = item.Part?.Name; var description = item.Description; if (string.IsNullOrEmpty(this.Part) && description == null) { description = item.InvoiceItemType.Name; } this.Description = description?.Split('\n'); this.Quantity = item.Quantity; this.Price = Rounder.RoundDecimal(item.UnitPrice, 2).ToString("N2", new CultureInfo("nl-BE")); this.Amount = Rounder.RoundDecimal(item.TotalExVat, 2).ToString("N2", new CultureInfo("nl-BE")); this.Comment = item.Comment?.Split('\n'); this.SupplierProductId = item.Part?.SupplierOfferingsWherePart?.FirstOrDefault(v => v.Supplier.Equals(item.PurchaseInvoiceWherePurchaseInvoiceItem.BilledFrom))?.SupplierProductId; }
/// <summary> /// Adjust percent discount,discount,percent fee and fee transaction /// </summary> /// <param name="target"> /// The target that will be adjusted. /// </param> /// <param name="type"> /// Type of adjustment. /// </param> /// <param name="input"> /// Adjustment amount. /// </param> public Adjustment(IAdjustable target, AdjustmentType type, Decimal input) { this.method = type; input = Math.Round(input, 2); this.requestValue = input; this.adjustedObject = target; this.adjustedTotal = target.TotalAmount; createdTime = DateTime.Now; if (cr.CurrentCashier != null) { authorizingCashierId = cr.CurrentCashier.Id; } /* * 0.0001m added because of math.round bug * for example: Math.Round(0.145, 2) = 0.14 * but Math.Round(0.1451,2) = 0.15 */ switch (type) { case AdjustmentType.Discount: netAmount = -1m * input; break; case AdjustmentType.PercentDiscount: requestValue = Math.Round(input, 0); netAmount = (-1m) * Rounder.RoundDecimal((input / 100) * target.TotalAmount + 0.0001m, 2, true); break; case AdjustmentType.Fee: netAmount = input; break; case AdjustmentType.PercentFee: requestValue = Math.Round(input, 0); netAmount = Rounder.RoundDecimal((input / 100) * target.TotalAmount + 0.0001m, 2, true); break; } }
public OrderItemModel(SalesOrderItem item) { var currencyIsoCode = item.SalesOrderWhereSalesOrderItem.DerivedCurrency.IsoCode; this.Reference = item.InvoiceItemType?.Name; this.Product = item.Product?.Name; var description = item.Description; if (description != null) { description = Markdown.ToPlainText(description); } this.Description = description?.Split('\n'); this.Quantity = item.QuantityOrdered; // TODO: Where does the currency come from? this.Price = Rounder.RoundDecimal(item.UnitPrice, 2).ToString("N2", new CultureInfo("nl-BE")); this.Amount = Rounder.RoundDecimal(item.TotalExVat, 2).ToString("N2", new CultureInfo("nl-BE")); this.Comment = item.Comment?.Split('\n'); }
public void ShouldNotRound() { var data = new List <Tuple <string, decimal> >() { Tuple.Create("a", 25m), Tuple.Create("b", 25m), Tuple.Create("c", 25m), Tuple.Create("d", 25m), }; var rounded = Rounder.round(data); rounded.First().Item1.Should().Be("a"); rounded.ElementAt(1).Item1.Should().Be("b"); rounded.ElementAt(2).Item1.Should().Be("c"); rounded.ElementAt(3).Item1.Should().Be("d"); rounded.First().Item2.Should().Be(25); rounded.ElementAt(1).Item2.Should().Be(25); rounded.ElementAt(2).Item2.Should().Be(25); rounded.ElementAt(3).Item2.Should().Be(25); }
void ProfitMath() { //profit + deposit math if (PositionOpen == true && Buying == true) { Profit = Rounder.RoundToHundredth((currentPrice - OpenPrice) * Quantity); //if (gameState == GameManager.GS.Play) Deposit -= comission; //Debug.Log("OP: " + economics.OpenPrice + " | Current Price: " + economics.CurrentPrice + " | Profit: " + economics.profit); } else if (PositionOpen == true && Buying == false) { Profit = Rounder.RoundToHundredth((OpenPrice - currentPrice) * Quantity); //if (gameState == GameManager.GS.Play) Deposit -= comission; //Debug.Log("OP: " + economics.OpenPrice + " | Current Price: " + economics.CurrentPrice + " | Profit: " + economics.profit); } else { Profit = 0; } //float oldDeposit = deposit; //Deposit = Mathf.Round(Deposit * 100) / 100; }
public void ShouldRoundTwoItems() { var data = new List <Tuple <string, decimal> >() { Tuple.Create("a", 25.6m), Tuple.Create("b", 25.6m), Tuple.Create("c", 24.4m), Tuple.Create("d", 24.4m), }; var rounded = Rounder.round(data); rounded.Sum(a => a.Item2).Should().Be(100); rounded.First().Item1.Should().Be("a"); rounded.ElementAt(1).Item1.Should().Be("b"); rounded.ElementAt(2).Item1.Should().Be("c"); rounded.ElementAt(3).Item1.Should().Be("d"); rounded.First().Item2.Should().Be(26); rounded.ElementAt(1).Item2.Should().Be(26); rounded.ElementAt(2).Item2.Should().Be(24); rounded.ElementAt(3).Item2.Should().Be(24); }
public void ShouldRoundSome() { var data = new List <Tuple <string, decimal> >() { Tuple.Create("Equities", 31.6220989654932m), Tuple.Create("Fixed Income", 55.8340786306896m), Tuple.Create("Alternatives", 2.88033373820556m), Tuple.Create("Cash", 9.66349214560435m), }; var rounded = Rounder.round(data); rounded.Sum(a => a.Item2).Should().Be(100); rounded.First().Item1.Should().Be("Equities"); rounded.ElementAt(1).Item1.Should().Be("Fixed Income"); rounded.ElementAt(2).Item1.Should().Be("Alternatives"); rounded.ElementAt(3).Item1.Should().Be("Cash"); rounded.First().Item2.Should().Be(31); rounded.ElementAt(1).Item2.Should().Be(56); rounded.ElementAt(2).Item2.Should().Be(3); rounded.ElementAt(3).Item2.Should().Be(10); }
public void When_Fraction_Is_Half_Then_Return_True(double value, bool expected) { Assert.AreEqual(expected, Rounder.IsFractionExactlyHalf(value)); }
public static IState Pay(Decimal amount) { List <String> promotionRemark = new List <string>(); if (amount != 0) { if (paymentInfo is CurrencyPaymentInfo) { paymentInfo.Amount = Rounder.RoundDecimal(amount * ((CurrencyPaymentInfo)paymentInfo).ExchangeRate, 2, true); } else { paymentInfo.Amount = amount; } } if (paymentInfo.MinimumPayment > paymentInfo.Amount) { throw new OverflowException("ÖDEME MÝKTARI\nLÝMÝTÝN ALTINDA"); } if (paymentInfo.MaximumPayment < paymentInfo.Amount) { throw new OverflowException("ÖDEME MÝKTARI\nLÝMÝTÝN ÜZERÝNDE"); } //Payment on eft pos try { if ((paymentInfo is CreditPaymentInfo) && (cr.EftPos != null) && (((CreditPaymentInfo)paymentInfo).Credit.PayViaEft)) { IEftResponse response = cr.EftPos.Pay(paymentInfo.Amount, ((CreditPaymentInfo)paymentInfo).Installments); if (response.HasError) { throw new Exception("Exception occured when payment via EftPos."); } ((CreditPaymentInfo)paymentInfo).IsPaymentMade = true; ((CreditPaymentInfo)paymentInfo).Remark = response.CardNumber; } } catch (Exception) { return(cr.State = States.ConfirmPayment.Instance(PosMessage.ACCEPT_PAYMENT_OR_REPEAT_VIA_EFT, new StateInstance <Decimal>(ComplateCreditPayment), new StateInstance(cancelState), new StateInstance <Decimal>(Pay))); } // Add using points after confirm if (paymentInfo is CreditPaymentInfo && ((CreditPaymentInfo)paymentInfo).Credit.IsPointPayment) { long usingPoint = cr.Document.PriceToPoint(paymentInfo.Amount * -1); cr.Document.AddPoint(usingPoint); } // Add promo document if (!cr.Document.CanEmpty) { cr.Document.Append(promoDocument); promoDocument = null; } if (paymentInfo.Amount >= cr.Document.BalanceDue) { promoDocument = null; } if (cr.Document.Status != DocumentStatus.Paying && cr.Document.Remark != null) { foreach (String remark in cr.Document.Remark) { cr.Printer.PrintRemark(remark); } } return(cr.Document.Pay(paymentInfo)); }
public void Rounding_Test_Three_Should_Not_Round() { var result = Rounder.Round(1.25M); Assert.AreEqual(1.25M, result); }
public void Rounding_Test_Four_Round_up() { var result = Rounder.Round(1.251M); Assert.AreEqual(1.30M, result); }
public void Rounding_Test_Two_Round_up() { var result = Rounder.Round(1.221M); Assert.AreEqual(1.25M, result); }
public void When_Passed_Zero_Should_Return_Zero() { var result = Rounder.Round(0M); Assert.AreEqual(0M, result); }
public Calculator(Rounder rounder) { this.rounder = rounder; }
public void ApplyPromotion() { decimal ratio = 0m; decimal lineDiscount = 0m, percDiscount = 0m; switch (base.LimitType) { case LimitType.Quantity: ratio = (int)(LineQuantity() / base.RequiredQuantity); lineDiscount = ratio * base.Discount; percDiscount = Rounder.RoundDecimal((TotalPercantageDiscount() / LineQuantity()) * (ratio * base.RequiredQuantity), 2, true); break; case LimitType.Amount: ratio = (TotalAmount() / base.RequiredAmount); lineDiscount = LineQuantity() * base.Discount; percDiscount = Rounder.RoundDecimal(TotalPercantageDiscount(), 2, true); break; default: ratio = LineQuantity(); lineDiscount = ratio * base.Discount; percDiscount = Rounder.RoundDecimal(TotalPercantageDiscount(), 2, true); break; } bool isPercentage = false; if (percDiscount > lineDiscount) { lineDiscount = percDiscount; isPercentage = true; } DataRow[] items = SoldItem.Instance().Select(String.Format("Plu = '{0}'", base.Id)); if (base.limitType != LimitType.Quantity && isPercentage) { foreach (DataRow rowItems in items) { rowItems["DiscountAmount"] = Rounder.RoundDecimal(((decimal)rowItems["Amount"] * base.PercentDiscount) / 100, 2, true); rowItems["PercentDiscount"] = base.PercentDiscount; } } else { decimal discItemQuantity = base.RequiredQuantity * ratio; decimal unitDisc = Rounder.RoundDecimal(lineDiscount / discItemQuantity, 2, true); decimal diff = lineDiscount - Rounder.RoundDecimal(unitDisc * discItemQuantity, 2, true); decimal amount = 0m; foreach (DataRow rowItems in items) { decimal lineDiscQuantity = (decimal)rowItems["Quantity"]; if (lineDiscQuantity <= 0) { continue; } int percRate = base.PercentDiscount; if ((decimal)rowItems["Quantity"] > discItemQuantity) { lineDiscQuantity = discItemQuantity; amount = (unitDisc * lineDiscQuantity) + diff; percRate = 0; } else { amount = (unitDisc * lineDiscQuantity) + diff; } diff = 0; discItemQuantity -= lineDiscQuantity; rowItems["DiscountAmount"] = (decimal)rowItems["DiscountAmount"] + amount; if (isPercentage) { rowItems["PercentDiscount"] = percRate; } if (discItemQuantity == 0) { break; } } } decimal appliedDisc = (decimal)SoldItem.Instance().Compute("Sum(DiscountAmount)", String.Format("Plu = '{0}'", base.Id)); pointEarned = (long)ratio * (base.Points + base.ExtraPoints); SoldItem.Instance().SetPromotion(this, appliedDisc + pointEarned > 0); }
public static void StartState(Rounder <TValue, TPrecision, TMidLabelPolicy> rounder, TPrecision etalonPrecision, TMidLabelPolicy etalonMidLabelPolicy) { Assert.AreEqual(rounder.Precision, etalonPrecision); Assert.AreEqual(rounder.MidLabelPolicy, etalonMidLabelPolicy); }