Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I parse Infinity with Double?

If I try

Double.Parse("Infinity")

I get

Double.Parse("Infinity") threw an exception of type 'System.FormatException'

Why? And what should I do if I want to parse it anyway and get a Double with the value Infinity?

like image 447
tomsv Avatar asked Nov 27 '22 17:11

tomsv


2 Answers

I just found this out:

Decimal.Parse("Infinity", System.Globalization.CultureInfo.InvariantCulture);

will work and return a double with the value +Infinity.

The reason it did not work is that I am not, I think, automatically in the InvariantCulture but perhaps in the de-DE culture which does not handle the exact string "Infinity". (Perhaps it would handle some other string.)

like image 61
tomsv Avatar answered Dec 09 '22 10:12

tomsv


All the below parsing are valid, since your system settings are different is causing the issue. As dontomaso had answered above just need to add the Invariant Culture.

Double.Parse("NaN", System.Globalization.CultureInfo.InvariantCulture)
Double.Parse("-Infinity", System.Globalization.CultureInfo.InvariantCulture)
Double.Parse("Infinity", System.Globalization.CultureInfo.InvariantCulture)
like image 24
Carbine Avatar answered Dec 09 '22 09:12

Carbine