I'm working on an importer for LitJson, to import float values from ints, and doubles, and if overflow-checking is enabled, I want to wrap a potential overflow exception in a JsonException with a bit more information about the failure.
Right now my code looks like this, and I don't know if I need to/can check if the context is checked or not:
private static float DoubleFloatImporter(double value) {
try
{
return (float)value;
}
catch (Exception ex)
{
throw new JsonException("Value is not a valid Single", ex);
}
}
You may be thinking of
checkedanduncheckedcontexts, but these are not relevant for your example, the explicit conversion (cast) fromdoubletofloat(so from double-precision binary floating point to single-precision).A finite
doublevalue may round to an infinitefloatvalue (eitherfloat.PositiveInfinityorfloat.NegativeInfinity).For example
DoubleFloatImporter(1.23e123). As a double, the input1.23e123will be represented as a finite value, but when cast tofloat, the nearest representable value will be interpreted as +∞.Edit: As I say in comments, something like:
may suit your need.