Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting object to long

Tags:

c#

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?

like image 949
mehdi.loa Avatar asked Mar 31 '26 22:03

mehdi.loa


1 Answers

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.

like image 87
Thorarin Avatar answered Apr 03 '26 13:04

Thorarin