Zidane
Zidane

Reputation: 1904

How do I successfully convert a double to string

I have a purchased amount that I am trying to convert from double to string and I keep getting an error that reads Input string was not in a correct format. on this line herevar amount = (ol.Amount*Convert.ToDouble(exchange)).ToString("0.##");

My Code

var exchange=GetNigerianExchange();
var amount = (ol.Amount*Convert.ToDouble(exchange)).ToString("0.##");





private static string GetNigerianExchange()
{
    var forex = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=ZAR&to_currency=NGN&apikey=ZRH58691ZX2ENX1U&datatype=json";
    var JsonResult = "";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(forex);
    request.ContentType = "application/json; charset=utf-8";
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    using (Stream responseStream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
        JsonResult = reader.ReadToEnd();
    }

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    dynamic jsonObject = serializer.Deserialize<dynamic>(JsonResult);

    dynamic x = jsonObject["Realtime Currency Exchange Rate"];
    var exchange = (string)jsonObject["Realtime Currency Exchange Rate"]["5. Exchange Rate"];

    return exchange;
}

Upvotes: 0

Views: 166

Answers (1)

Nastassia Lukyanovich
Nastassia Lukyanovich

Reputation: 11

You receive exchange rate from external source. So "Input string was not in a correct format" error can happen when you try convert rate string to double. Use TryParse instead of just Convert to safely convert string to double if possible.

var exchange=GetNigerianExchange();
double exchangeRate = 1;
if (!Double.TryParse(value, out exchangeRate)) {
    // do something for case when you cannot convert rate to double
}

var amount = (ol.Amount * exchangeRate).ToString("0.##", CultureInfo.InvariantCulture);

Upvotes: 1

Related Questions