Search code examples
c#xbee

How can i convert double to another double C#?


How to convert 30.55273 to 30.055273 in C# i am working with xbee wireless module and it doesn't send fraction numbers so i have to cut any double value into two parts EX: 30.055273 -> 30 and 055273 so when i send both of them i receive them 30 and 55273 so the zero on the left will be canceled how can i fix this problem


Solution

  • It sounds like you're receiving two integers, which you want to stick together - with one of them scaled by a factor of a million. Is that right?

    double ConvertToDouble(int wholePart, int fractionalPart)
    {
        return wholePart + fractionalPart / 1000000d;
    }
    

    Note that the "d" part is very important - it's to make sure you perform the division using double arithmetic (instead of integer arithmetic).

    If the exact digits are important to you, it's possible that you should actually be using decimal:

    decimal ConvertToDouble(int wholePart, int fractionalPart)
    {
        return wholePart + fractionalPart / 1000000m;
    }