I have the following function:
public virtual long AsLong(object originalValue,long defaultValue)
{
double buffer = defaultValue;
if (originalValue != null)
{
double result;
var readValueIsconverted = double.TryParse(originalValue.ToString(), out result);
if (readValueIsconverted)
buffer = result;
}
var roundedValue = Math.Round(buffer, 0);
var convertedValue = (long) roundedValue;
return convertedValue;
}
I have used double in order to allow conversion of 14.4! I have the following failing test:
[Fact]
public void CanConvertLongMaxValue()
{
var cellValue = new Converter();
const long longValue = 0x7FFFFFFFFFFFFFFF;
var result = cellValue.AsLong(longValue, 12);
Assert.Equal(longValue, result);
}
I have traced the code and roundedValue is positive but the convertedValue is negative. so what is the problem?
The problem is that you're trying to hold an integer value with 19 significant digits (in decimal) in a double which has 15-16 significant digits.
Hence, it's not possible to represent the value exactly in the double. Apparently rounding causes the value to overflow when converted into a long, making it a negative value.
You can confirm this like so:
var convertedValue = checked((long)roundedValue);
If you absolutely must deal with this case, I would suggest using decimal instead of double, or splitting the string on the decimal point (or whatever is used in your locale) and dealing with rounding that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With