Search code examples
c#conventions

wrong format to convert to a double, looks ok to me any idea?


keep getting error saying string in wrong format, it looks right to me. anyone know what's wrong with it?

var pound = donation.Text;
        // convert euro to pound
       var euro = (Convert.ToDouble(dontaion_euro.Text));
        var convertion_rate = 0.83;
        var converted = euro * convertion_rate;

solved with

 dontaion_euro.Text = "00.00";

            var euro = Convert.ToDecimal(dontaion_euro.Text);
            var convertion_rate = Convert.ToDecimal(00.83); 
            var converted = euro * convertion_rate;

Solution

  • You could get this error if dontaion_euro.Text is not a valid number. I'd suggest you validate the inputs before you use them in calculations. I'd suggest you use specific type if you could when you know the types in advance.

    This example shows how to validate an input

    // Parse currency value using en-GB culture. 
    value = "£1,097.63";
    style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
    culture = CultureInfo.CreateSpecificCulture("en-GB");
    if (Decimal.TryParse(value, style, culture, out number))
       Console.WriteLine("Converted '{0}' to {1}.", value, number);
    else
       Console.WriteLine("Unable to convert '{0}'.", value);
    // Displays:  
    //       Converted '£1,097.63' to 1097.63.
    

    Source: MSDN-TryParse Example.