Splitting double to primary and float

Hello,

I have a code that processes coordinates as 4 separate double variables (e.g. 51, 1822, 22, 2234). However, the data is stored as 2 separate double variables (e.g. 51.1822 and 22.2234)

The Whole number is always 2. and the fractions range between 1 to 6 digits.

So, how may I separate the right and left digits of the decimal point and store each into separate double variables please-?

Thank you.

The actual number of digits after the decimal point will always be the same. You must decide how many digits are significant

Why do you want the results in double variables when they will, by definition, be integers ?

void setup()
{
  Serial.begin(115200);
  double v1 = 51.1822;
  int v2 = (v1 / 100) * 100;
  unsigned long v3 = (v1 - v2) * 100000000;
  Serial.println(v1, 8);
  Serial.println(v2);
  Serial.println(v3);
}

void loop()
{
}

if you mean to store into a c-string array, then something like this could work for you:

void setup() {
  Serial.begin(115200);

  char c_str[16]; //ensure array is big enough to store all the characters that will form the c-string
  float d1 = 51.1822;
  float d2 = 22.2234;

  //store d1 and d2 as c-string
  //values 'written' to 4dp. 
  //values seperated by comma (',')
  sprintf(c_str, "%s,%s", String(d1, 4).c_str(), String(d2, 4).c_str());

  //replace all '.' with ','
  char *fnd_chr = strchr(c_str, '.');
  while (fnd_chr) {
    *fnd_chr = ',';
    fnd_chr = strchr(fnd_chr, '.');
  }

  Serial.println(c_str);

}

void loop() {
  // put your main code here, to run repeatedly:

}

output

51,1822,22,2234

hope that helps...

how about

12  345

double x = 12.3456;

// -----------------------------------------------------------------------------
void setup (void)
{
    Serial.begin (9600);

    int i = int(x);
    int f = int(1000*(x-i));

    Serial.print   (i);
    Serial.print   ("  ");
    Serial.println (f);
}

// -----------------------------------------------------------------------------
void loop (void)
{
}

That did it. Thank you.

===>

 double x = 12.3456;
 int i = int(x);      //12
 int f = int(10000*(x-i));`  //3456

to get 12 and 3456 from 12.3456?

1 Like

How?

You are expecting 51 and 1822 from the sketch of post #2 @UKHeliBob; but, the sketch delivers the following output:

51.18220138
51
18220138

was left for the OP to figure out

Also for the readers! :slight_smile:

As I alluded to in my post, @vaxman was expecting the wrong thing as a double value has a fixed number of decimal places rather than a variable number. It is the number of significant decimal places that matters

don't you want to be able to control the # of decimal digits to display? how many decimal digits of Pi would you want to display?

Usually, we are happy with 3.14.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.