public async Task <PagedResponse <PrintingEditionModel> > GetPageAsync(PaginationRequest <PrintingEditionFilter> page) { var printingEditions = await _printingEditionRepository.GetPageAsync(page); var mapped = _mapper.Map <IEnumerable <PrintingEditionModel> >(printingEditions); var response = new PagedResponse <PrintingEditionModel> { Data = mapped, PageNumber = page.PageNumber, PageSize = page.PageSize, HasNextPage = printingEditions.HasNextPage, HasPreviousPage = printingEditions.HasPreviousPage }; if (page.Filter is null || page.Filter.Currency is null) { return(response); } foreach (var item in mapped) { item.Price = _converter.Convert(item.Price, item.Currency, page.Filter.Currency); item.Currency = (CurrencyType)page.Filter.Currency; } return(response); }
public void currencyConvertionWithinSameCurrencyReturnsSameAmount() { double amount = 100; converter .Convert("INR", amount, "INR").Should().Be(amount); }
public void NormalCurrencyConversion() { //setup var mock = new Mock <RateProvider>(); RateProvider r = mock.Object; //when GetRate() called with parameter ("USD","SGD") returns 1.4 mock.Setup(x => x.GetRate("USD", "SGD")).Returns(1.4); CurrencyConverter c = new CurrencyConverter(r); //exercise double result = c.Convert("USD", 100, "SGD"); //verify double expected = 140; Assert.AreEqual(expected, result); mock.Setup(x => x.GetRate("USD", "SGD")).Returns(1.5); result = c.Convert("USD", 100, "SGD"); expected = 150; Assert.AreEqual(expected, result); mock.Setup(x => x.GetRate("USD", "XXX")).Throws(new InvalidOperationException()); }
public void WhenInputHasWrongFormat_CallConverter_ReceiveErrorMessage(string input) { var result = _target.Convert(input); Assert.IsNotNull(result.ErrorMessage); Assert.IsNull(result.Result); }
public void Convert_ShouldReturnAmountIfFromAndToAreSame() { var fromAmount = 100; var toAmount = converter.Convert("INR", fromAmount, "INR"); Assert.AreEqual(fromAmount, toAmount); }
public void ConversionTestFromTRY() { var response1 = converter.Convert(Currency.TRY, 252M, Currency.EUR); var response2 = converter.Convert(Currency.TRY, 232M, Currency.GBP); Assert.True(response1 % roundStep == 0); Assert.True(response1 > 0); Assert.True(response2 % roundStep == 0); Assert.True(response2 > 0); }
public void ShouldConvertDecimalToCurrency() { CurrencyConverter converter = new CurrencyConverter(); decimal? numDecimal = 20; var convertedValue = converter.Convert(numDecimal, typeof(decimal?), null, null) as string; Assert.AreEqual("$20.00", convertedValue); convertedValue = converter.Convert(null, null, null, null) as string; Assert.AreEqual("$0.00", convertedValue); }
public ActionResult Cart() { //if (Session["Cart"] == null) //{ // Session["Cart"] = new List<Movie>(); //} //var movies = ((List<Movie>) Session["Cart"]); //var currencyConverter = new CurrencyConverter(Session["Currency"].ToString()); //foreach (var movie in movies) //{ // movie.Price = currencyConverter.Convert(movie.Price); //} //return PartialView(movies); if (Session["Cart"] == null) { Session["Cart"] = new List <Movie>(); } var movies = new List <Movie>(); var currencyConverter = new CurrencyConverter(Session["Currency"].ToString()); foreach (var movie in ((List <Movie>)Session["Cart"])) { movies.Add(new Movie() { Title = movie.Title, Price = currencyConverter.Convert(movie.Price), PicturePath = movie.PicturePath }); } return(PartialView(movies)); }
public void TestConvertWithThousandths() { var model1 = new CurrencyConverter() { InputNumber = "999,999,999.99" }; var model2 = new CurrencyConverter() { InputNumber = "999999999.99" }; var convertResult1 = model1.Convert(); Assert.IsNotNull(convertResult1); Assert.IsTrue(convertResult1.IsSuccessful); var convertResult2 = model2.Convert(); Assert.IsNotNull(convertResult2); Assert.IsTrue(convertResult2.IsSuccessful); Assert.AreEqual("Nine Hundred and Ninety Nine Million Nine Hundred and Ninety Nine Thousand Nine Hundred and Ninety Nine Dollars and Ninety Nine Cents", convertResult1.Data, "Thousandths should be allowed to input"); Assert.AreEqual(convertResult1.Data, convertResult2.Data, "Numbers with thousandths should be read the same as the numbers without thousandths"); }
static async Task Main(string[] args) { // Parse exchange rates var xchangeParser = new ExchangeRateParser(); var rates = xchangeParser.CsvToExchangeRates( await File.ReadAllTextAsync("ExchangeRates.csv")); // Parse products var productParser = new ProductParser(); var products = productParser.CsvToProducts( await File.ReadAllTextAsync("Prices.csv")); // Look for product var product = products.FirstOrDefault(p => p.Description == args[0]); if (product == null) { Console.WriteLine("Sorry, product not found"); return; } var converter = new CurrencyConverter(rates); Console.WriteLine($"{converter.Convert(product.Price, product.Currency, args[1]),0:0.00}"); }
private IStakingPower MapStakingPower(IStakeSettings stakeInfo, DataStakingPower stakePower, CurrencyCode currencyCode) { return(new BusinessStakingPower() { Symbol = stakeInfo.Symbol, Date = stakePower?.Date ?? stakeInfo.InceptionDate, Power = CurrencyConverter.Convert(stakePower?.Power ?? decimal.Zero, currencyCode), Summary = stakePower?.Summary .Select(fs => new BusinessStakingPowerSummary() { Symbol = GetFunds() .Single(x => x.ContractAddress.Address.Equals(fs.ContractAddress, StringComparison.OrdinalIgnoreCase)) .Symbol, Power = CurrencyConverter.Convert(fs.Power, currencyCode), }) .ToList() ?? new List <BusinessStakingPowerSummary>(), Breakdown = stakePower?.Breakdown .Select(fp => new BusinessStakingPowerFund() { Symbol = GetFunds() .Single(x => x.ContractAddress.Address.Equals(fp.ContractAddress, StringComparison.OrdinalIgnoreCase)) .Symbol, FundModifier = fp.FundModifier, Quantity = fp.Events.Sum(x => x.Quantity), ModifiedQuantity = fp.Events.Sum(x => x.Quantity * x.TimeModifier * fp.FundModifier), Power = CurrencyConverter.Convert(fp.PricePerToken * fp.Events.Sum(x => x.Quantity * x.TimeModifier * fp.FundModifier), currencyCode), }) .ToList() ?? new List <BusinessStakingPowerFund>() }); }
public async Task ConvertsCurrency() { // Arrange var grpcClientMock = TestMocks.GrpcClientMock(); // Act var currencyConverter = new CurrencyConverter(grpcClientMock); const double expectedTotalRoi = 750; const double expectedTotalFees = 75; var roiResult = new RoiCalculationResult() { Currency = TestConstants.BaseCurrency, Total = 1000, Fees = 100, }; await currencyConverter.Convert(roiResult, TestConstants.BaseCurrency, TestConstants.TargetCurrency); // Assert Assert.AreEqual(roiResult.Total, expectedTotalRoi); Assert.AreEqual(roiResult.Fees, expectedTotalFees); }
string MoneyToCurrency(PriceСurrency currency, decimal money) { if (money == 0) { return(String.Empty); } string toCurrency; string fromCurrency = currency.ToString(); if (currencyMode == CurrencyMode.Edit) { toCurrency = currency.ToString(); } else { toCurrency = currencyMode.ToString(); } if (fromCurrency.CompareTo(toCurrency) != 0) { var converted = CurrencyConverter.Convert(money, fromCurrency, toCurrency); if (converted == null) { return(String.Empty); } money = converted.Value; } return(String.Format("{0:N2} {1}", money, toCurrency)); }
public new Profit ConvertToCurrency(string targetCurrency) { if (CurrencyConverter == null) { throw new NullReferenceException("Для текущего объекта денег не указан конвертер валют."); } return(CurrencyConverter.Convert(this, targetCurrency)); }
public ActionResult Index(int id) { var currencyConverter = new CurrencyConverter(Session["Currency"].ToString()); var movie = facade.GetMovieGateway().ReadById(id); movie.Price = currencyConverter.Convert(movie.Price); return(View(movie)); }
private async Task <BusinessFundAsset> MapFundAssetAsync(FundSettings.FundAsset asset, decimal fundValue, CurrencyCode currencyCode) { var sanitisedId = asset.Name.Replace(" ", "-").Replace(".", "-").ToLower().Trim(); var coinloreId = GetAssetInfo(asset.Symbol)?.CoinLore ?? sanitisedId; var coinGecko = GetAssetInfo(asset.Symbol)?.CoinGecko; var coinMarketCapId = GetAssetInfo(asset.Symbol)?.CoinMarketCap ?? sanitisedId; var assetInfo = GetAssetInfo(asset.Symbol); var contractAddress = !string.IsNullOrWhiteSpace(asset.ContractAddress) ? new EthereumAddress(asset.ContractAddress) : default(EthereumAddress?); var marketValuePerToken = default(decimal?); if (contractAddress.HasValue) { marketValuePerToken = assetInfo?.PoolAddress == null ? (await ethplorerClient.GetTokenInfoAsync(contractAddress.Value)).Price?.MarketValuePerToken : await graphClient.GetUniswapPriceAsync(assetInfo.PoolAddress.Value, contractAddress.Value); } if (coinGecko != null && !marketValuePerToken.HasValue) { marketValuePerToken = (await coinGeckoClient.GetCoinAsync(coinGecko)).Market.Price.Value; } var total = asset.Quantity != default && marketValuePerToken.HasValue ? CurrencyConverter.Convert(marketValuePerToken.Value * asset.Quantity, currencyCode) : CurrencyConverter.Convert(asset.Value, currencyCode); return(new BusinessFundAsset() { Holding = new BusinessHolding() { Name = asset.Name, Symbol = asset.Symbol, HexColour = GetAssetInfo(asset.Symbol)?.Colour, ContractAddress = !string.IsNullOrEmpty(asset.ContractAddress) ? new EthereumAddress(asset.ContractAddress) : default(EthereumAddress?), Decimals = asset.Decimals, IsCoin = asset.IsCoin, Link = assetInfo?.PoolAddress != null ? new Uri(string.Format(PoolTemplate, assetInfo.PoolAddress.Value), UriKind.Absolute) : asset.Link ?? new Uri(string.Format(LinkTemplate, coinMarketCapId), UriKind.Absolute), ImageLink = asset.ImageLink ?? new Uri(string.Format(ImageTemplate, coinloreId), UriKind.Absolute), MarketLink = asset.Tradable ? new Uri(string.Format(MarketTemplate, coinloreId, currencyCode), UriKind.Absolute) : null }, Quantity = asset.Quantity, PricePerToken = marketValuePerToken ?? decimal.Zero, Total = total, Share = total / fundValue * 100 }); }
public List <Result> Convert(string input) { var _data = new List <Result>(); try { var converter = new CurrencyConverter(); _data.Add(new Result() { Header = "Currency" , Description = $"{converter.Convert(input).ToString(CultureInfo.InvariantCulture)}" }); } catch (Exception e) { Console.WriteLine(e); } if (input.Length > 6 && input.Substring(0, 6).ToUpper().Trim() == "BASE64") { var baseConverter = new Base64Converter(); _data.Add(new Result() { Header = "Base64", Description = baseConverter.TryConvertFrom(input.Substring(7, input.Length - 7)).Output }); _data.Add(new Result() { Header = "Base64", Description = baseConverter.TryConvertTo(input.Substring(7, input.Length - 7)).Output }); } else if (input.Length > 3 && (input.Substring(input.Length - 2, 2) == "==" || input.Substring(input.Length - 1, 1) == "=")) { var baseConverter = new Base64Converter(); _data.Add(new Result() { Header = "Base64", Description = baseConverter.TryConvertFrom(input).Output }); } if (!_data.Any()) { _data.Add(new Result() { Header = ":(", Description = "Try something else.." }); } return(_data); }
private decimal GetBalance(IEnumerable <Transaction> transactions) { var currencyConverter = new CurrencyConverter(); string code = GetCurrencyCode(); decimal sum = 0; foreach (var transaction in transactions) { if (transaction.Type == (int)OperationType.Debit) { sum -= (decimal)(transaction.Cost * currencyConverter.Convert(transaction.Currency.Code, code)); } else { sum += (decimal)(transaction.Cost * currencyConverter.Convert(transaction.Currency.Code, code)); } } return(sum); }
public void TestConvertNegativeNumber() { var model = new CurrencyConverter() { InputNumber = "-1.151" }; var convertResult = model.Convert(); Assert.IsNotNull(convertResult); Assert.IsTrue(convertResult.IsSuccessful); Assert.AreEqual("Negative One Dollar and Fifteen Cents", convertResult.Data); model.InputNumber = "-1.155"; convertResult = model.Convert(); Assert.IsNotNull(convertResult); Assert.IsTrue(convertResult.IsSuccessful); Assert.AreEqual("Negative One Dollar and Sixteen Cents", convertResult.Data); }
public void TestConvertWithTooLongInput() { var model = new CurrencyConverter() { InputNumber = "99,999,999,999,999,999,999,999,999.990" }; var convertResult = model.Convert(); Assert.IsNotNull(convertResult); Assert.IsFalse(convertResult.IsSuccessful); Assert.AreEqual("Please input a number which has maximum 28 digits", convertResult.ResultMessage, "If input string has more than 28 digits, error message should be displayed"); model.InputNumber = "99,999,999,999,999,999,999,999,999.99"; convertResult = model.Convert(); Assert.IsNotNull(convertResult); Assert.IsTrue(convertResult.IsSuccessful); Assert.AreEqual(string.Empty, convertResult.ResultMessage, "If input string is a valid number with (<=28) digits, error message should not be displayed"); }
private static int MakeConversion(Content content) { var currencyConverter = new CurrencyConverter(content.ExchangeRates); var convertedAmount = currencyConverter.Convert( content.Conversion.Amount, content.Conversion.From, content.Conversion.To); return(convertedAmount.Rounded); }
public void TestCurrencyConverter() { Mock <RateRetriever> r = new Mock <RateRetriever>(); r.Setup(x => x.GetCurrentRateFromYahooFinance("USD", "SGD")).Returns(1.4); CurrencyConverter c = new CurrencyConverter(r.Object); double result = c.Convert("USD", "SGD", 100); Assert.AreEqual(140, result); }
public async Task <PriceDto> GetAsync([FromRoute] string productDesc, [FromQuery] string targetCurrency) { CurrencyConverter cc = new CurrencyConverter(); ParseCsv parser = new ParseCsv(); var(exchangeRateFileContent, productPricesFileContent) = await fileReader.ReadCsvAsync(); List <ExchangeRate> exchangeRates = parser.CsvExchangeRateParser(exchangeRateFileContent); List <Product> products = parser.CsvProductParser(productPricesFileContent); return(new PriceDto(cc.Convert(products.Find(p => p.Description == productDesc), exchangeRates, targetCurrency))); }
public void ConverterTest() { Assert.AreEqual(testEUR * amount, CurrencyConverter.Convert(amount, "EUR")); Assert.AreEqual(testUAH * amount, CurrencyConverter.Convert(amount, "UAH")); Assert.AreEqual(testGBP * amount, CurrencyConverter.Convert(amount, "GBP")); Assert.AreEqual(testEUR * 0, CurrencyConverter.Convert(0, "EUR")); Assert.AreEqual(testUAH * 0, CurrencyConverter.Convert(0, "UAH")); Assert.AreEqual(testGBP * 0, CurrencyConverter.Convert(0, "GBP")); Assert.AreNotEqual(1, CurrencyConverter.Convert(0, "EUR")); Assert.AreNotEqual(2, CurrencyConverter.Convert(0, "UAH")); Assert.AreNotEqual(0.1f, CurrencyConverter.Convert(0, "GBP")); }
public void TestConvertWithOutOfRangeData() { var model = new CurrencyConverter() { InputNumber = "100,000,000,000,000,000,000,000,000" }; var convertResult = model.Convert(); Assert.IsNotNull(convertResult); Assert.IsFalse(convertResult.IsSuccessful); Assert.AreEqual("The number input should between -99999999999999999999999999.99 and 99999999999999999999999999.99", convertResult.ResultMessage, "If input number is not in [-99999999999999999999999999.99, 99999999999999999999999999.99], error message should be displayed"); model.InputNumber = "99,999,999,999,999,999,999,999,999.99"; convertResult = model.Convert(); Assert.IsNotNull(convertResult); Assert.IsTrue(convertResult.IsSuccessful); Assert.AreEqual(string.Empty, convertResult.ResultMessage, "If input number is a valid number in [-99999999999999999999999999.99, 99999999999999999999999999.99], error message should not be displayed"); }
public void TestConvertZero() { var model = new CurrencyConverter() { InputNumber = "0" }; var convertResult = model.Convert(); Assert.IsNotNull(convertResult); Assert.IsTrue(convertResult.IsSuccessful); Assert.AreEqual("Zero", convertResult.Data); }
public void ConvertTest() { CurrencyConverter.Prices[Currency.PLN] = 1; CurrencyConverter.Prices[Currency.USD] = 3.89; for (double i = -100; i < 100; i += 0.001) { double actual = CurrencyConverter.Convert(Currency.PLN, Currency.USD, i); double expected = i / 3.89; Assert.AreEqual(expected, actual); } }
public async Task Currency(CommandContext ctx, [Description("Input currency in ISO")] Currency inCurrency, [Description("Output currency in ISO")] Currency outCurrency, [Description("Amount to convert")] double amount) { if (ctx.Channel.Get(ConfigManager.Enabled) .And(ctx.Channel.GetMethodEnabled())) { await ctx.TriggerTypingAsync(); await ctx.RespondAsync( $"{amount} {inCurrency.CurrencyName} equals {CurrencyConverter.Convert(amount, inCurrency, outCurrency)} {outCurrency.CurrencyName}"); } }
public async Task <bool> Transfer(Card from, Card to, decimal amount) { LastError = ""; NpgsqlConnection connection = new NpgsqlConnection(connectionString); try { await connection.OpenAsync(); CurrencyConverter converter = new CurrencyConverter(); NpgsqlCommand cmd = new NpgsqlCommand("INSERT INTO public.\"Transfers\" (\"user_id_from\", \"user_id_to\",\"amount\"" + ",\"card_id_from\",\"card_id_to\",\"date_time\",\"currency\") VALUES ((@userIdFrom), (@userIdTo), (@amount)" + ",(@cardIdFrom),(@cardIdTo),(@dt),(@currency))", connection); decimal convertedAmount = converter.Convert(from.Currency, to.Currency, amount); cmd.Parameters.AddWithValue("userIdFrom", from.HolderUserId); cmd.Parameters.AddWithValue("userIdTo", to.HolderUserId); cmd.Parameters.AddWithValue("amount", convertedAmount); cmd.Parameters.AddWithValue("cardIdFrom", from.Id); cmd.Parameters.AddWithValue("cardIdTo", to.Id); cmd.Parameters.AddWithValue("dt", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")); cmd.Parameters.AddWithValue("currency", to.Currency); await cmd.ExecuteNonQueryAsync(); cmd = new NpgsqlCommand("UPDATE public.\"Cards\" SET balance = balance - (@t_amount) WHERE id = (@id)", connection); cmd.Parameters.AddWithValue("t_amount", amount); cmd.Parameters.AddWithValue("id", from.Id); await cmd.ExecuteNonQueryAsync(); cmd = new NpgsqlCommand("UPDATE public.\"Cards\" SET balance = balance + (@t_amount) WHERE id = (@id)", connection); cmd.Parameters.AddWithValue("t_amount", convertedAmount); cmd.Parameters.AddWithValue("id", to.Id); await cmd.ExecuteNonQueryAsync(); return(true); } catch (Exception e) { LastError = e.Message; return(false); } finally { await connection.CloseAsync(); } }
public ActionResult Index() { /** var numbers = new List<int> { 1, 2, 3, 4, 10, 5 }; * var idk = numbers.First(number => number > 4); **/ var db = new DB(); var currency1 = db.Currencies.First(c => c.Id == 1); // taking the first currency var currency2 = db.Currencies.First(c => c.Id == 2); // taking the second currency CurrencyConverter.Convert(currency1, currency2, 100); return(View()); }
public double computeTotalCost(String weight, String selectedDeliveryService, String currencyType) { double[] getWeightRate; double[] getRateCost; Boolean exist=false; PostageCharge DeliveryNames = null; CurrencyConverter cc = new CurrencyConverter(currencyTxtPath); foreach (PostageCharge e in this.pcEntries) { if (DeliveryNames == null) if (e.DeliveryService.Equals(selectedDeliveryService, System.StringComparison.OrdinalIgnoreCase)) { DeliveryNames = e; } } if (DeliveryNames != null) { foreach (PostageCharge e in this.pcEntries) { if (e.DeliveryService.Equals(selectedDeliveryService, System.StringComparison.OrdinalIgnoreCase)) { this.getWeightRateString = e.Weight.Split(','); this.getRateCostString = e.RateCost.Split(','); } } getWeightRate = new double[this.getWeightRateString.Length]; getRateCost = new double[this.getRateCostString.Length]; for (int i = 0; i < this.getWeightRateString.Length; i++) { getWeightRate[i] = double.Parse(this.getWeightRateString[i]); } for (int i = 0; i < this.getRateCostString.Length; i++) { getRateCost[i] = double.Parse(this.getRateCostString[i]); } for (int i = 0; i < getWeightRate.Length; i++) { if (double.Parse(weight) <= getWeightRate[i]) { exist = true; return cc.Convert(currentCurrencyType, double.Parse(weight) * getWeightRate[i], currencyType); } } if (!exist) { return cc.Convert(currentCurrencyType, ((double.Parse(weight) / 100) * getWeightRate[getWeightRate.Length - 1]), currencyType); } exist = false; } return -1; }