Abdelrahman Elshafiey
Abdelrahman Elshafiey

Reputation: 105

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

Upvotes: 0

Views: 150

Answers (4)

Reem
Reem

Reputation: 43

Building on Bloack Frog's idea. Construct a string in c# Then cast it to double as follows:


String result = leftToDecimal.ToString() 
+ "." + zeroString(numberOfZeros) + fraction.ToString();
 double MyOriginalNumber = Convert.ToDouble(result);

Public string zeroString(int zeroCount)
{
   String result= "";
   for(int i=0; i< zeroCount; i++)
   result+="0";
}

Upvotes: 1

Keith Nicholas
Keith Nicholas

Reputation: 44316

just choose a multiplier, like 100000, take the fractional part and multiply it by that number, then later divide by that number.

Also, you can send whatever data you like over XBee. You may just want to convert your data into an array of bytes. See How do I convert an array of floats to a byte[] and back? on how to do that.

Upvotes: 2

Black Frog
Black Frog

Reputation: 11725

Can you send them as a string? Then do that.

If you can only send integer values, then send 3 values.

For example: 30.055273

  • First number is left of decimal (whole number)
  • Second number is right of decimal (fraction)
  • Third number is the number of zeros (placeholder)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503090

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;
}

Upvotes: 3

Related Questions