Exception in .ToString("F3")

Hello,
I found a strange behavior in the ToString() function.

Reproducible code:

        // initialization
        string strText;
        double dblTemperature;

        dblTemperature = 0.09999;
        strText = dblTemperature.ToString("F3");
        Debug.WriteLine("Value 1: " + strText);

        dblTemperature = -0.09999;
        strText = dblTemperature.ToString("F3");
        Debug.WriteLine("Value 2: " + strText);

        dblTemperature = 0.099999999999999978;
        strText = dblTemperature.ToString("F3");
        Debug.WriteLine("Value 3: " + strText);

(dblTemperature can assume any value between -5 and 65)
It works always except when dblTemperature contains the value: 0.099999999999999978 where the .ToString(“F3”) statement throws an exception.

The code output is the following:

Value 1: 0.100
Value 2: -0.100
#### Exception System.Exception - CLR_E_WRONG_TYPE (1) ####
#### Message:
#### System.String::get_Chars [IP: 0000] ####
#### System.Number::ReplaceNegativeSign [IP: 0005] ####
#### System.Number::PostProcessFloat [IP: 0018] ####
#### System.Number::Format [IP: 0143] ####
#### System.Double::ToString [IP: 002e] ####
Generated Exception: ‘System.Exception’ in mscorlib.dll
Uncought Exception of type ‘System.Exception’ in mscorlib.dll

I don’t know if there are other cases. What can be the reason?

I’m using TinyCLR V2.1.0 on SCM20260.

Thanks in advance for any suggestion.

2 Likes

I have submitted this before and I think I also understand what’s happening.

It seems like the double is handled as a float when parsing to a string. So if your double contains too much decimals then you get the exception because it can’t be handled as a float.

If my memory serves me right, this will be fixed next release. Until then you can cast your double to a float and then print it, that has worked for me! :slight_smile:

3 Likes

Hi Luca,
I just tried it and it worked!
Thanks a lot for your suggestion.

Vittorio

1 Like