Search code examples
f#formatexception

Input String was not in a correct format in F#


Could anyone tell me and explain to me what's wrong with this code?

open System
let hexarea t:float =
    (3.0*Math.Sqrt(3.0)/2.0) * Math.Pow(t, 2.0)
let value = float (Console.ReadLine())
let calc = hexarea value
printfn "%f" calc

I can give a hint - it works when it's like:

open System
let hexarea t : float =
    (3.0 * Math.Sqrt(3.0) / 2.0) * Math.Pow(t,2.0)
[<EntryPoint>]  
    let main argv =
    let value = float (Console.ReadLine())
    let calc  = hexarea value
    printf "%f" calc
    0

By the way, if I remove 0 from the last line, it's complaining..

Please clarify to me what's happening.

Thanks.


Solution

  • If you are getting "Input String was not in a correct format" exception as the title of your question suggests, this is likely because the number you are entering in the Console.ReadLine is not in the correct format.

    This is a continuous pain-point if you're from a country that uses decimal comma rather than decimal dot. In Czech, we write 3,14 and so if you set the current culture to cs-CZ you get:

    System.Threading.Thread.CurrentThread.CurrentCulture <- 
      System.Globalization.CultureInfo.GetCultureInfo("cs-CZ")
    
    float "1.0" // Works because this uses invariant culture
    System.Double.Parse("1.0") // Fails because this uses cs-CZ culture now
    
    float "1,0" // Fails because the invariant culture requires .
    System.Double.Parse("1,0") // Works according to cs-CZ culture