I find it occasionally necessary to represent integral values with floating-point numeric types. Some reasons why this may be necessary include, but are not limited to:
Compatibility with legacy code
A need to represent infinities and/or NaN with integral values
Desire to use a single field to hold a value that could be integral or floating-point, depending on the scenario
In such cases it would be helpful to have the constants MinSafeInteger and MaxSafeInteger defined in the floating-point numeric types to know if an integral value could be represented safely in the given type. "Safely" in this context refers to the ability to represent integers exactly and to compare them correctly.
This proposal is identical in concept to the corresponding APIs in JavaScript.
API Proposal
namespace System;
public readonly struct Double
{
public const double MinSafeInteger = -9007199254740991d; // -(2^53-1)
public const double MaxSafeInteger = 9007199254740991d; // 2^53-1
}
public readonly struct Single
{
public const double MinSafeInteger = -16777215f; // -(2^24-1)
public const double MaxSafeInteger = 16777215f; // 2^24-1
}
API Usage
double value = ...;
if (value >= double.MinSafeInteger && value <= double.MaxSafeInteger)
{
// value can safely be represented in double
}
else
{
// nope
}
Background and motivation
I find it occasionally necessary to represent integral values with floating-point numeric types. Some reasons why this may be necessary include, but are not limited to:
In such cases it would be helpful to have the constants
MinSafeInteger
andMaxSafeInteger
defined in the floating-point numeric types to know if an integral value could be represented safely in the given type. "Safely" in this context refers to the ability to represent integers exactly and to compare them correctly.This proposal is identical in concept to the corresponding APIs in JavaScript.
API Proposal
API Usage
Alternative Designs
No response
Risks
No response