简体   繁体   English

如何将double转换为另一个double C#?

[英]How can i convert double to another double C#?

如何在C#中将30.55273转换为30.055273,我正在使用xbee无线模块,并且它不发送分数,所以我必须将任何double值切成两部分,例如:30.055273-> 30和055273,所以当我同时发送它们时,我收到30和55273,所以左侧的零将被取消我该如何解决此问题

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). 请注意,“ d”部分非常重要-确保使用double精度算术(而不是整数算术)执行除法。

If the exact digits are important to you, it's possible that you should actually be using decimal : 如果确切的数字对您来说很重要,则实际上您可能应该使用decimal

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

just choose a multiplier, like 100000, take the fractional part and multiply it by that number, then later divide by that number. 只需选择一个乘数,例如100000,取小数部分,然后乘以该数字,然后再除以该数字即可。

Also, you can send whatever data you like over XBee. 另外,您可以通过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? 请参阅如何将浮点数组转换为byte []并返回? on how to do that. 关于如何做到这一点。

Can you send them as a string? 您可以将它们作为字符串发送吗? Then do that. 然后做。

If you can only send integer values, then send 3 values. 如果只能发送整数值,则发送3个值。

For example: 30.055273 例如: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) 第三个数字是零的数量(占位符)

Building on Bloack Frog's idea. 建立在Bloack Frog的想法上。 Construct a string in c# Then cast it to double as follows: 在c#中构造一个字符串,然后将其转换为double,如下所示:


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM